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

ggplot配对柱状图重叠问题:如何分离两组柱状图?

解决配对柱状图重叠问题

你的问题出在用宽格式数据分两次调用geom_bar绘图,这种方式没法让ggplot识别分组来自动错开柱子,所以才会重叠。正确的做法是先把数据转成长格式,再用单组geom_bar实现分组错开。

步骤1:把宽格式数据转成长格式

用tidyr包的pivot_longer函数,把AvgAUPre(Before)和AvgAUPost(After)合并成一个分组列:

# 如果没装tidyr先安装:install.packages("tidyr")
library(tidyr)
library(ggplot2)

# 转换数据格式
fish_long <- fish %>%
  pivot_longer(
    cols = c(AvgAUPre, AvgAUPost),  # 要合并的目标列
    names_to = "Time",              # 新分组列的名称
    values_to = "AreaUse",          # 数值列的名称
    # 把原列名映射成Before/After
    names_transform = list(Time = ~ifelse(. == "AvgAUPre", "Before", "After"))
  )

步骤2:用长格式数据绘图

现在只需要一次geom_bar,让ggplot根据Time分组自动错开柱子:

ggplot(fish_long, aes(x = Treat, y = AreaUse, fill = Time)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  labs(x = "Treatment", y = "Area Use", fill = "Time") +
  scale_fill_manual(values = c("Before" = "lightblue", "After" = "orange")) +
  theme_minimal()

为什么这样能解决问题?

转成长格式后,Time成为明确的分组变量,ggplot会自动为每个Treat下的Before和After柱子计算错开位置,不需要手动调整两个geom_bar的position参数,自然不会出现重叠。

内容的提问来源于stack exchange,提问作者Hau Janice

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:24:57