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

geom_col绘制柱形图y值异常问题求助

ggplot柱形图与计算均值不符的问题排查与解决

背景信息

  • 分析目标:探究反应时(rt_mean)与组内分类变量Assignment(Yourself/Stranger)的关系,每个被试对应多条rt_mean记录
  • 数据示例:
participant Assignment rt_mean
         <dbl> <chr>        <dbl>
 1     7148832 Yourself      601.
 2     7148832 Yourself      554.
 3     7148832 Yourself      604.
 4     7148832 Stranger      810.
 5     7148832 Stranger      821.
 6     7148832 Stranger      712.
 7     7148833 Yourself      651.
 8     7148833 Yourself      725.
 9     7148833 Yourself      784.
10     7148833 Stranger      693.
  • 手动计算均值:mean_yourself = 686.2,mean_stranger = 749.3
  • 问题现象:用geom_col()绘制的柱形图中,Yourself柱形高于Stranger(与计算结果相反)且数值偏高,但geom_boxplot()显示正常

问题原因

geom_col()的默认行为是将同一x分组下的所有y值堆叠求和,而非计算均值。从数据示例看,Yourself的记录条数(6条)多于Stranger(4条),即使单条均值更低,总和依然更大,导致柱形高度与手动计算的均值趋势完全相反。

解决办法

方法1:先汇总均值再绘图(推荐,逻辑清晰)

先通过分组统计得到每个Assignment的均值,再基于汇总后的数据绘图:

# 分组计算均值
reaction_time_summary <- reaction_time %>%
  dplyr::group_by(Assignment) %>%
  dplyr::summarize(rt_mean_avg = mean(rt_mean, na.rm = TRUE))

# 绘制柱形图
reaction_time_plot <- reaction_time_summary %>%
  ggplot2::ggplot(aes(x = Assignment, y = rt_mean_avg, fill = Assignment)) +
  geom_col(position = position_dodge()) +
  labs(x = "Assignment", y = "Reaction Time in ms") +
  theme_bw() +
  scale_fill_manual(values = c("#ABB0B8", "#4C4E52"))
reaction_time_plot

方法2:直接在绘图时指定统计变换

使用stat_summary()替代geom_col(),直接在图层中指定计算均值:

reaction_time_plot <- reaction_time %>%
  ggplot2::ggplot(aes(x = Assignment, y = rt_mean, fill = Assignment)) +
  stat_summary(fun = mean, geom = "col", position = position_dodge()) +
  labs(x = "Assignment", y = "Reaction Time in ms") +
  theme_bw() +
  scale_fill_manual(values = c("#ABB0B8", "#4C4E52"))
reaction_time_plot

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:35:22