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

如何为分组变量通过stat_summary修改均值点与误差棒颜色

方法二:手动汇总数据后绘制

若偏好手动计算统计量,需保证均值点、误差棒的分组偏移与散点一致,解决间距问题:

set.seed(123)
var_y = rnorm(n  = 100, mean = 3)
var_x = rep(c("A", "B"), each = 50)
var_col = c(rep("a", times = 50), rep("b", times = 50))

df <- data.frame(var_x, var_y, var_col)

library(ggplot2)
library(dplyr)

# 分组汇总均值与标准差,取消分组避免后续警告
description <- df |> 
  group_by(var_x, var_col) |> 
  summarise(mean_groups = mean(var_y),
            sd_groups = sd(var_y),
            .groups = "drop")

ggplot() +
  geom_point(data = df, aes(x = var_x, y = var_y, colour = var_col), 
             alpha = .3, position = position_dodge(.5)) +
  # 均值点:指定group保证偏移,设置为黑色
  geom_point(data = description, aes(x = var_x, y = mean_groups, group = var_col), 
             position = position_dodge(.5), size = 3, color = "black") +
  # 误差棒:指定group与散点同偏移,设置为黑色
  geom_errorbar(data = description, aes(x = var_x, 
                                        ymin = mean_groups - sd_groups, 
                                        ymax = mean_groups + sd_groups,
                                        group = var_col), 
                position = position_dodge(.5), width = 0.1, color = "black") +
  scale_color_manual(values = c("darkgreen", "darkred"))

关键说明:

  • 汇总时添加.groups = "drop"清除分组状态,避免ggplot警告
  • 均值点与误差棒的aes中指定group = var_col,并使用和散点相同的position_dodge(.5),确保分组偏移对齐
  • 直接设置color = "black"统一均值点与误差棒颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:42:50