作者:黄天元,复旦大学博士在读,热爱数据科学与开源工具(R),致力于利用数据科学迅速积累行业经验优势和科学知识发现,涉猎内容包括但不限于信息计量、机器学习、数据可视化、应用统计建模、知识图谱等,著有《R语言数据高效处理指南》。知乎专栏:R语言数据挖掘。邮箱:huang.tian-yuan@qq.com.欢迎合作交流
R中很多调色板,但是它们能够提供的色彩都不够用(多只有大概12种)。为了获得更多,查了很多资料,想办法可以生成任意数量的离散型能相互区分的色彩。
方法一:
library(RColorBrewer)
getPalette = colorRampPalette(brewer.pal(9, "Set1"))
scale_color_manual(values = getPalette(18)) #要18个离散颜色
参考资料:How to expand color palette with ggplot and RColorBrewer
方法二:
drsimonj_colors <- c(
`red` = "#d11141",
`green` = "#00b159",
`blue` = "#00aedb",
`orange` = "#f37735",
`yellow` = "#ffc425",
`light grey` = "#cccccc",
`dark grey` = "#8c8c8c")
drsimonj_cols <- function(...) {
cols <- c(...)
if (is.null(cols))
return (drsimonj_colors)
drsimonj_colors[cols]
}
drsimonj_palettes <- list(
`main` = drsimonj_cols("blue", "green", "yellow"),
`cool` = drsimonj_cols("blue", "green"),
`hot` = drsimonj_cols("yellow", "orange", "red"),
`mixed` = drsimonj_cols("blue", "green", "yellow", "orange", "red"),
`grey` = drsimonj_cols("light grey", "dark grey")
)
scale_fill_drsimonj <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
pal <- drsimonj_pal(palette = palette, reverse = reverse)
if (discrete) {
discrete_scale("fill", paste0("drsimonj_", palette), palette = pal, ...)
} else {
scale_fill_gradientn(colours = pal(256), ...)
}
}
scale_fill_drsimonj(palette = "mixed", guide = "none")
参考资料:Creating corporate colour palettes for ggplot2 • blogR
近发现了一种新方法,记录在:微笑牛油果:R语言作图:自定义调色盘