如何在ggplot中按盐浓度拆分堆叠柱状图?
解决ggplot堆叠柱状图拆分问题
要让0%和3%盐处理的柱子分开显示(并列而非堆叠),你需要调整ggplot的分组和位置参数,以下是修正后的代码:
library(tidyverse) # 创建数据集 Strain <- c('Saltgrass', 'Saltgrass','Saltgrass', 'Saltgrass', 'Pickleweed', 'Pickleweed','Pickleweed', 'Pickleweed') SaltConcentration <- c(0,0,3,3,0,0,3,3) Generation <- c('Generation 1', 'Generation 5', 'Generation 1', 'Generation 5','Generation 1', 'Generation 5', 'Generation 1', 'Generation 5') Growth <- c(2,4,1,3,2,4,3,5) HypoDF <- data.frame(Strain, SaltConcentration, Generation, Growth) # 修正后的绘图代码 ggplot(data= HypoDF, mapping = aes(x= Generation, y= Growth, fill= Strain, group= interaction(Strain, SaltConcentration), color= Strain))+ geom_col(position = position_dodge(width = 0.8)) + labs(x = "世代", y = "生长量", fill = "菌株", color = "菌株") + theme_minimal()
关键修改说明:
- 修复语法错误:原代码中
aes()里的color,是无效写法,必须给该参数赋值(这里设为和fill一致的Strain,让柱子边框和填充色对应)。 - 明确分组规则:用
interaction(Strain, SaltConcentration)让ggplot根据「菌株+盐浓度」的组合来分组,确保同世代下不同处理的柱子能被区分。 - 启用并列模式:添加
position = position_dodge(width = 0.8),让同x轴(世代)下的分组柱子并列显示,width参数可调整柱子间的间距。
额外优化建议:
把SaltConcentration转为因子类型,能让图表分组逻辑更清晰,也方便添加自定义标签:
HypoDF$SaltConcentration <- factor(HypoDF$SaltConcentration, labels = c("0%盐浓度", "3%盐浓度")) # 也可以把盐浓度整合到x轴,更直观展示分组 ggplot(data= HypoDF, mapping = aes(x= interaction(Generation, SaltConcentration), y= Growth, fill= Strain, color= Strain))+ geom_col(position = position_dodge(width = 0.8)) + labs(x = "世代+盐浓度", y = "生长量", fill = "菌株", color = "菌株") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
这样就能完全拆分不同盐处理的柱子,每个分组下会清晰展示对应菌株的生长量对比。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

