nic*_*ole 5 color-scheme r colors ggplot2
我想为堆叠的条形图着色,以便每个条形图都有自己的父颜色,每个条形图中的颜色都是此父颜色的渐变.
例:
这是一个最小的例子.我希望每个条形的颜色不同color
,每个条形内的渐变由"清晰度"设置.
library(ggplot2)
ggplot(diamonds, aes(color)) +
geom_bar(aes(fill = clarity), colour = "grey")
Run Code Online (Sandbox Code Playgroud)
在我真正的问题中,我每组都有更多的组:需要18种不同的条形,有39种不同的渐变颜色.
我ColourPalleteMulti
创建了一个函数,它允许您根据数据中的子组创建多个颜色托盘:
ColourPalleteMulti <- function(df, group, subgroup){
# Find how many colour categories to create and the number of colours in each
categories <- aggregate(as.formula(paste(subgroup, group, sep="~" )), df, function(x) length(unique(x)))
category.start <- (scales::hue_pal(l = 100)(nrow(categories))) # Set the top of the colour pallete
category.end <- (scales::hue_pal(l = 40)(nrow(categories))) # set the bottom
# Build Colour pallette
colours <- unlist(lapply(1:nrow(categories),
function(i){
colorRampPalette(colors = c(category.start[i], category.end[i]))(categories[i,2])}))
return(colours)
}
Run Code Online (Sandbox Code Playgroud)
从本质上讲,该函数可识别您拥有的不同组,然后计算每组中的颜色数.然后它将所有不同的调色板连接在一起.
要使用调色板,最简单的方法是添加一个新列group
,它将用于制作调色板的两个值粘贴在一起:
library(ggplot2)
# Create data
df <- diamonds
df$group <- paste0(df$color, "-", df$clarity, sep = "")
# Build the colour pallete
colours <-ColourPalleteMulti(df, "color", "clarity")
# Plot resultss
ggplot(df, aes(color)) +
geom_bar(aes(fill = group), colour = "grey") +
scale_fill_manual("Subject", values=colours, guide = "none")
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您希望每个条形图中的条形图不同,则可以更改用于绘制条形图的变量的方式:
# Plot resultss
ggplot(df, aes(cut)) +
geom_bar(aes(fill = group), colour = "grey") +
scale_fill_manual("Subject", values=colours, guide = "none")
Run Code Online (Sandbox Code Playgroud)
注意事项:诚实地说,您想要绘制的数据集可能包含太多子类别,因此无法使用.
此外,虽然这在视觉上非常令人愉悦,但我建议避免使用这样的色标.它更多的是使绘图看起来漂亮,并且不同的颜色是多余的,因为我们已经知道数据来自X轴的哪个组.