如何为ggplot2多个分类堆叠柱形图设置统一图例与配色
统一堆叠柱形图配色的ggplot2实现
问题背景
我通过for循环生成5个堆叠柱形图,涉及0-9共10个因子,但并非每个图都包含所有因子。希望为各图设置统一配色(如所有'1'为浅绿色、所有'9'为灰色),现有如下colLegend配色列表,需将其应用到当前ggplot2绘图代码中:
colLegend <- list('0' = '#A9CCE3', # light blue '1' = '#A3E4D7', # light green '2' = '#27AE60', # DARK GREEN '3' = '#F7DC6F', # YELLOW '4' = '#F8C471', # ORANGE '5' = '#D35400', # RED '6' = '#117864', # DARK TEAL '7' = '#AF7AC5', # PURPLE '8' = '#2E4053', # NAVY '9' = '#616A6B') # GREY
当前绘图代码:
## plot stacked percentage of each value labels <- c('19', '20', '22') # create tally of each Ellenberg value j = 1 for (df in ellenCatTab){ dfName <- names(ellenCatTab)[j] j = j + 1 df = df[,5:31] tidy <- df %>% gather(key='Quadrat', value='Ellenberg') tidy <- na.omit(tidy) tally <- tidy %>% count(Quadrat, Ellenberg) tally$Ellenberg <- as.factor(tally$Ellenberg) tally <- as.data.table(tally) tally[, c('Q', 'Year') := tstrsplit(tally$Quadrat, "_", fixed=TRUE)][] tally$Q <- sub('X', 'Q', tally$Q) stacked <- ggplot(tally, aes(fill=Ellenberg, y=n, x=Quadrat)) + geom_bar(position='stack', stat='identity') + ggtitle(dfName) + labs(x='Year', y='Number of Plants') + scale_x_discrete(labels=labels) + theme_classic() + facet_wrap(~ Q, nrow=1, scales='free_x') plot(stacked) ggsave(plot=stacked, file=paste0(dfName, '_stacked.png'), limitsize=FALSE, width=250, height=200, units='mm') }
解决方案
要实现跨图的统一配色,只需在ggplot代码中添加scale_fill_manual()函数,将预定义的配色规则传入即可。关键步骤如下:
- 将
colLegend列表转换为向量格式(scale_fill_manual接受向量参数):
colVec <- unlist(colLegend)
- 在ggplot的绘图代码中,添加
scale_fill_manual()配置:values = colVec:指定各因子对应的颜色- 可选
limits = names(colLegend):强制所有图的图例显示完整的0-9因子,即使当前图未包含该因子,确保图例样式完全统一
修改后的完整代码如下:
## plot stacked percentage of each value labels <- c('19', '20', '22') # 将配色列表转为向量 colVec <- unlist(colLegend) # create tally of each Ellenberg value j = 1 for (df in ellenCatTab){ dfName <- names(ellenCatTab)[j] j = j + 1 df = df[,5:31] tidy <- df %>% gather(key='Quadrat', value='Ellenberg') tidy <- na.omit(tidy) tally <- tidy %>% count(Quadrat, Ellenberg) tally$Ellenberg <- as.factor(tally$Ellenberg) tally <- as.data.table(tally) tally[, c('Q', 'Year') := tstrsplit(tally$Quadrat, "_", fixed=TRUE)][] tally$Q <- sub('X', 'Q', tally$Q) stacked <- ggplot(tally, aes(fill=Ellenberg, y=n, x=Quadrat)) + geom_bar(position='stack', stat='identity') + ggtitle(dfName) + labs(x='Year', y='Number of Plants') + scale_x_discrete(labels=labels) + # 应用统一配色,可选limits参数保证图例统一 scale_fill_manual(values = colVec, limits = names(colLegend)) + theme_classic() + facet_wrap(~ Q, nrow=1, scales='free_x') plot(stacked) ggsave(plot=stacked, file=paste0(dfName, '_stacked.png'), limitsize=FALSE, width=250, height=200, units='mm') }
说明
- 若不需要显示完整的0-9因子图例,可移除
limits = names(colLegend)参数,此时每个图的图例仅显示当前图存在的因子,但配色仍保持统一 colVec的命名与Ellenberg因子的取值完全对应,确保每个因子在所有图中都映射到相同的颜色
内容的提问来源于stack exchange,提问作者Melanie Baker
相关产品推荐
相关产品推荐

