GGplot堆叠柱状图优化求助:Y轴刻度、层级顺序、水平线显示
问题解决方案
1. 扩展Y轴刻度至70,000,000
使用scale_y_continuous()手动指定刻度集合,包含目标总数值70000000,同时可设置合理的刻度间隔:
scale_y_continuous(breaks = c(0, 14000000, 28000000, 42000000, 56000000, 70000000), limits = c(0, 70000000))
2. 固定堆叠层级顺序
将Source列转换为有序因子,指定levels = c("bedload", "suspended"),ggplot会按照因子定义的顺序堆叠(先定义的层级在底部)。同时确保填充色顺序与因子层级对应:
# 预处理数据的因子顺序 SedimentLoad$Source <- factor(SedimentLoad$Source, levels = c("bedload", "suspended")) # 填充色与层级对应(bedload对应浅灰,suspended对应深灰) scale_fill_manual(values = c("#CCCCCC","#666666"))
3. 修复geom_hline不显示问题
原Y轴范围未完全覆盖堆叠后的总高度(70000000),导致水平线可能因轴范围自动截断而不显示。通过上述scale_y_continuous()设置limits = c(0, 70000000)后,Y轴范围明确包含19000000,水平线会正常渲染。
修改后的完整代码
# 预处理数据的因子顺序 SedimentLoad$Source <- factor(SedimentLoad$Source, levels = c("bedload", "suspended")) plt1 <- ggplot() + geom_bar(aes(y = Volume, x = Scenario, fill = Source), data = SedimentLoad, stat = "identity") + # 设置Y轴刻度、范围,可选添加千分位分隔符优化可读性 scale_y_continuous(breaks = c(0, 14000000, 28000000, 42000000, 56000000, 70000000), limits = c(0, 70000000), labels = scales::comma) + scale_fill_manual(values = c("#CCCCCC","#666666")) + labs(fill = "Source", x = "Scenario", y = "Volume (m³)") + theme_classic() + # 移除重复的theme_bw,避免样式冲突 theme(text=element_text(size=8, family = "Arial")) + geom_hline(yintercept = 19000000, linetype=3) plt1
内容的提问来源于stack exchange,提问作者mpearson
相关产品推荐
相关产品推荐

