在ggplot2分面分组条形图中设置同色系不同色调
问题:为分面分组条形图设置同色系不同色调
现有代码
temp.data = data.frame ( Species = rep(c("A","B"),each=2, times=2), Status = rep(c("An","Bac"), times=4), Sex = rep(c("Male","Female"), each=4, times=1), Proportion = c(6.86, 7.65, 30.13, 35.71, 7.13, 10.33, 29.24, 31.09) ) ggplot(temp.data, aes(x = Species, y = Proportion, fill = Status, alpha = Species)) + geom_bar(stat='identity', position = position_dodge(width = 0.73), width=.67) + facet_grid(Sex ~ .) + xlab("X title") + ylab("Y title") + scale_fill_manual(name = "Status", labels = c("An","Bac"), values = c("#86a681","#0a3e03")) + scale_alpha_manual(values = c(0.6, 1)) + theme_light() + theme( legend.title= element_text(size = 8), legend.title.align=0.5, legend.position = c(), legend.background=element_blank(), legend.text=element_text(size=7), legend.key.size = unit(0.6, 'cm'), axis.title.x = element_text(size = 9), axis.title.y = element_text(size = 9), axis.title.y.right = element_text("Sex of groups"), strip.background = element_rect( color="lightgrey", fill="white", size=0.5, linetype="solid"), strip.text.y = element_text(color = "darkgrey", face = "bold") )
当前效果
每个Status对应固定颜色,通过透明度区分Species,呈现同色不同透明度的条形。
期望效果
每个Status下,不同Species对应同色系的不同深浅颜色(而非透明度差异),比如An组的A是浅绿、B是深绿,Bac组的A是更深的浅绿、B是最深的绿,保持同色系内的色调区分。
解决方案
核心思路是让fill映射到Status和Species的组合,为每个组合手动指定同色系颜色,替代透明度区分的方案。
修改后的代码
temp.data = data.frame ( Species = rep(c("A","B"),each=2, times=2), Status = rep(c("An","Bac"), times=4), Sex = rep(c("Male","Female"), each=4, times=1), Proportion = c(6.86, 7.65, 30.13, 35.71, 7.13, 10.33, 29.24, 31.09) ) ggplot(temp.data, aes(x = Species, y = Proportion, fill = interaction(Status, Species))) + geom_bar(stat='identity', position = position_dodge(width = 0.73), width=.67) + facet_grid(Sex ~ .) + xlab("X title") + ylab("Y title") + scale_fill_manual( name = "Status", labels = c("An (A)", "An (B)", "Bac (A)", "Bac (B)"), values = c("#b8d8b4", "#86a681", "#3a6b34", "#0a3e03") # 同色系渐变颜色 ) + theme_light() + theme( legend.title= element_text(size = 8), legend.title.align=0.5, legend.position = "right", legend.background=element_blank(), legend.text=element_text(size=7), legend.key.size = unit(0.6, 'cm'), axis.title.x = element_text(size = 9), axis.title.y = element_text(size = 9), axis.title.y.right = element_text("Sex of groups"), strip.background = element_rect( color="lightgrey", fill="white", size=0.5, linetype="solid"), strip.text.y = element_text(color = "darkgrey", face = "bold") )
关键修改说明
- 填充映射调整:将
fill从Status改为interaction(Status, Species),让每个(Status, Species)组合对应独立的填充色。 - 同色系颜色设置:在
scale_fill_manual的values中,为每个组合指定同色系渐变颜色,确保同一Status下的Species颜色属于同一色系但深浅不同。 - 移除透明度设置:不再需要
alpha映射,直接用颜色深浅区分不同Species。
如果需要更规整的图例分组(比如按Status分组显示),可以额外使用guide_legend或ggnewscale包优化图例展示。
内容的提问来源于stack exchange,提问作者DSA
相关产品推荐
相关产品推荐

