分享

ggplot配色怎么弄

 生物_医药_科研 2019-07-16

花花写于2019.7.16 最近刚搬进人才公寓,各种采购和玩耍,非常开心,工作也开始步入正轨,慢慢安定下来,不知不觉断更了一周,赶紧的补起来。。。

知识点

ggplot2的默认配色分两类,一类是连续型变量对应的渐变色,一类是离散型变量对应的独立的几种颜色。

数据

(生信星球公众号后台回复color即可拿到示例数据)
用于分类的列是class

head(test)
# V1 patients class
# 1 1061        A     1
# 2 1548        A     2
# 3 2283        A     3
# 4 4756        A     4
# 5 1473        B     1
# 6 1760        B     2
table(test$class)

# 1  2  3  4 
#10 10 10 10 

做条形图

if(!require(ggplot2))install.packages('ggplot2')
library(ggplot2)
ggplot(data=test)+
  geom_bar(aes(x=patients,y=V1,fill=class),stat = 'identity')

直接做出来的图是这样的:


颜色从深蓝到浅蓝渐变,是连续型变量对应的颜色。验证一下:
str(test)
#'data.frame':    40 obs. of  3 variables:
# $ V1      : int  1061 1548 2283 4756 1473 1760 593 4062 722 435 ...
# $ patients: chr  'A' 'A' 'A' 'A' ...
# $ class   : int  1 2 3 4 1 2 3 4 1 2 ...

不出所料,class这一列的数据类型是整型

实际上我们想要的是独立的几种颜色,那么对数据类型进行转换是最直接的办法。

test$class=as.character(test$class)

再次运行作图代码:

ggplot(data=test)+
  geom_bar(aes(x=patients,y=V1,fill=class),stat = 'identity')

手动改颜色

注意这里是fill,不是color,color是边框。
颜色还可以手动修改,rgb颜色无数种任你选择,比如这样:

ggplot(data=test)+
  geom_bar(aes(x=patients,y=V1,fill=class),stat = 'identity')+
  scale_fill_manual(values = c('#EEE685','#FFC1C1', '#D8BFD8', '#D1EEEE'))+
  theme_bw()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多