You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:05:30