解决ggplot中geom_col正负Y值柱形堆叠重叠问题
解决ggplot正负值柱形堆叠重叠问题
问题根源
你当前的代码使用了多个geom_col调用,而position_stack()仅对同一个geom内部的分组生效,多个geom的元素会互相覆盖而非堆叠。同时宽格式的数据结构也不匹配ggplot的堆叠逻辑,这是导致350深度处BNight数据被覆盖的核心原因。
修复步骤
1. 将宽格式数据转换为长格式
使用tidyr包的pivot_longer函数,把分散的列整合为物种、时段、观测值的结构化长数据:
library(tidyr) library(dplyr) df_long <- df %>% pivot_longer( cols = -Depth, names_to = c("Species", "Time"), names_pattern = "(.)(Day|Night)", values_to = "Observations" ) %>% mutate(Species = paste0("Species ", Species))
2. 重新绘制堆叠柱形图
使用单个geom_col,依托长格式数据的分组逻辑实现正确堆叠,正负值会自动向上下两个方向堆叠:
library(ggplot2) ggplot(df_long, aes( x = factor(Depth, levels = c("1000", "850", "350", "200", "75")), y = Observations, fill = Species )) + geom_col(position = position_stack()) + scale_y_continuous(breaks = seq(-40, 40, 5), limits = c(-40, 40)) + labs(title = "CTA Spring", x = "Transect Depth (m)", y = "Observations", fill = "Species") + coord_flip() + geom_hline(yintercept = 0, linetype = "dashed") + theme_classic() + theme( axis.text.y = element_text(size = 15), axis.text.x = element_text(size = 12) )
关键说明
- 长格式数据让ggplot能识别同一深度下的所有观测值,自动按物种分组堆叠
- 单个
geom_col配合position_stack()会正确区分正负值:正值向上堆叠,负值向下堆叠,彻底解决覆盖问题 - 通过
factor(Depth, levels = ...)提前设置深度的显示顺序,替代原代码的xlim(),避免轴标签顺序混乱
内容的提问来源于stack exchange,提问作者Leah
相关产品推荐
相关产品推荐

