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

如何在ggplot2散点图(Dot Plots)中添加均值条与抖动效果?

解决方案:给三组数据添加抖动点与均值条

优化后的完整代码

first <- c(1, 1.2, 2, 3, 4)
second <- c(5, 6, 7, 8, 9)
third <- c(10, 16, 17, 18, 19)

# 一次性构建包含三组数据的数据集,将类别转为因子保证展示顺序
df <- data.frame(
  Value = c(first, second, third),
  Cat = factor(c(rep("first", length(first)), 
                 rep("second", length(second)),
                 rep("third", length(third))))
)

library(ggplot2)

# 绘制带抖动点和均值条的图表
ggplot(df, aes(x = Cat, y = Value, color = Cat)) +
  # 抖动点:避免同组数据重叠,width控制横向抖动幅度
  geom_jitter(width = 0.2, size = 2) +
  # 均值条:自动计算每组均值,以横向短条展示
  stat_summary(fun = mean, geom = "crossbar", 
               width = 0.3, color = "black", linewidth = 0.8) +
  xlab("") +
  theme_minimal()

关键步骤说明

  • 数据集简化:无需重复创建df,一次性整合三组数据,同时将Cat转为因子类型,确保类别按预设顺序展示。
  • 抖动效果实现:用geom_jitter()替代geom_point(),通过width参数调整横向抖动范围,解决同组数据点重叠的问题。
  • 均值条添加:stat_summary()会自动按分组计算均值,geom = "crossbar"指定绘制横向均值条,通过width、color等参数调整样式,让均值标记更清晰。

可选:带误差范围的均值展示

如果需要同时展示均值的误差范围(比如标准误),可以使用以下代码:

ggplot(df, aes(x = Cat, y = Value, color = Cat)) +
  geom_jitter(width = 0.2, size = 2) +
  # 绘制标准误误差条
  stat_summary(fun.data = mean_se, geom = "errorbar", 
               width = 0.3, color = "black", linewidth = 0.8) +
  # 叠加均值点
  stat_summary(fun = mean, geom = "point", color = "black", size = 3) +
  xlab("") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:01:07