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

ggplot2中dodge参数失效求助:分组柱状图重叠如何解决?

解决ggplot2柱状条重叠问题

你的问题出在多次调用geom_bar,每个图层的position='dodge'是独立生效的,三个图层的柱子没有共享分组逻辑,所以会重叠。ggplot2的分组柱状图需要基于长格式数据实现,只需要一个geom_bar图层就能解决。

步骤1:转换数据格式

先把你的宽格式数据(每列对应一个组别)转成长格式,用tidyr::pivot_longer函数:

# 加载所需工具包
library(ggplot2)
library(tidyr)

# 将宽格式数据转为长格式
correct.data_long <- pivot_longer(correct.data3, 
                                  cols = c(Both, Control, Treatment),  # 指定要转换的列
                                  names_to = "Group",  # 新列:存储组别名称
                                  values_to = "Correct_Count")  # 新列:存储正确答题数

步骤2:绘制分组柱状图

用转换后的长格式数据绘图,将fill映射到组别,配合position='dodge'实现并排柱子:

ggplot(correct.data_long, aes(x = Question, y = Correct_Count, fill = Group)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +  # width可调整柱子间距
  labs(title = "Correct Responses",
       y = "Number of Correct Responses",
       fill = "Treatment Group") +
  theme_bw()

补充说明

  • position_dodge(width = 0.9)里的width参数可以手动调整柱子间的间距,0.9是默认值,可根据需求改成0.8或1之类的数值。
  • 长格式数据是ggplot2的标准输入格式,后续做其他可视化也会更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:04:58