这个需求真的太常见了!注意问题强调的几个关键词:一是快速,二是大量,三是差异明显。在生成大量元素比较图时要明显区分不同样本,比如宏基因组中的物种分析:
image.png
方法一:自定义
自定义颜色:优点是选择差异明显的颜色,缺点是费时费力,不知选多少种,眼睛都要挑花。
R的颜色板很多网站都可以查,随意搜一个贴上:https://www.sojson.com/rgb.html
cb_palette <- c("#ed1299", "#09f9f5", "#246b93", "#cc8e12", "#d561dd", "#c93f00", "#ddd53e",
"#4aef7b", "#e86502", "#9ed84e", "#39ba30", "#6ad157", "#8249aa", "#99db27", "#e07233", "#ff523f",
"#ce2523", "#f7aa5d", "#cebb10", "#03827f", "#931635", "#373bbf", "#a1ce4c", "#ef3bb6", "#d66551",
"#1a918f", "#ff66fc", "#2927c4", "#7149af" ,"#57e559" ,"#8e3af4" ,"#f9a270" ,"#22547f", "#db5e92",
"#edd05e", "#6f25e8", "#0dbc21", "#280f7a", "#6373ed", "#5b910f" ,"#7b34c1" ,"#0cf29a" ,"#d80fc1",
"#dd27ce", "#07a301", "#167275", "#391c82", "#2baeb5","#925bea", "#63ff4f")
方法二:RColorBrewer包
利用RColorBrewer包中的面板。
library(RColorBrewer)
display.brewer.all()
查看颜色面板有:
image.png
从中选择颜色区分差异大的面板,也是需要自己挑选,而且数目相对较少:
brewer.pal(9, "Set1") #只有9个
c(brewer.pal(9, "Set1") ,brewer.pal(9, "Set3") ) #也可结合,但颜色区分不大,数目也还是少
colorRampPalette(c("red", "green"))(5)
rainbow(60) #彩虹色很容易生成,但数目一多很难区分,因为是渐变的。
可以结合这些面板,稍微处理下筛选:
library(RColorBrewer)
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
#处理后有73种差异还比较明显的颜色,基本够用
col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
#看下中间60种颜色的效果
pie(rep(1,n), col=sample(col_vector, 60))
image.png
方法二得到的图:
image.png
方法三:randomcoloR
综合来说,这种方法是最合适的吧,也最省代码。但颜色太多的话,必定是有很多近似的。而且这种方法不能重复得到结果,因为是随机生成的嘛,即使设置种子也不行。
library(randomcoloR)
palette <- randomColor(count = 60) #随机生成60种颜色,其实里面有重复的
palette <- distinctColorPalette(60) #差异明显的60种
这个问题貌似很难完美解决,毕竟主要的颜色也就那么几种。以下是第三种方法得到的图:
image.png
网友评论