花花写于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()
|