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

ggplot2:在双变量个体数据散点图中添加带标准误的组均值标记

解决方案

shape=3的加号属于统一缩放的点标记,无法单独调整横、竖臂的长度,最优实现方案是组合geom_errorbar(生成对应y变量标准误的竖臂)和geom_errorbarh(生成对应x变量标准误的横臂),具体步骤如下:

1. 修正汇总统计代码,补充标准误计算

在原有的均值计算基础上,新增x、y变量的标准误统计:

library(dplyr)
library(ggplot2)
DataMean <- Data %>% 
  group_by(Group) %>% 
  summarise(
    x = mean(x, na.rm = TRUE),
    y = mean(y, na.rm = TRUE),
    # 新增x、y的标准误计算
    x_se = sd(x, na.rm = TRUE)/sqrt(n()),
    y_se = sd(y, na.rm = TRUE)/sqrt(n())
  )

2. 替换原均值点图层为误差棒组合

去掉原geom_point绘制的加号标记,新增两个误差棒图层,通过width=0和height=0参数去掉误差棒两端的多余横线,仅保留中间的杆,组合后就是对应标准误长度的十字标记:

ggplot(Data, aes(x = x, y = y, shape = as.factor(Group), color = as.factor(Group))) +
  geom_point(alpha = 0.6) + # 原始散点,调低透明度突出均值标记
  # 竖臂:对应y的标准误
  geom_errorbar(
    data = DataMean,
    aes(ymin = y - y_se, ymax = y + y_se),
    width = 0, # 去掉误差棒两端的小横线
    size = 1.2 # 调整十字粗细
  ) +
  # 横臂:对应x的标准误
  geom_errorbarh(
    data = DataMean,
    aes(xmin = x - x_se, xmax = x + x_se),
    height = 0, # 去掉误差棒两端的小横线
    size = 1.2
  )

可复现测试示例(基于iris数据集)

你可以直接运行以下代码查看效果:

iris %>% 
  group_by(Species) %>% 
  summarise(
    x = mean(Sepal.Length),
    y = mean(Petal.Length),
    x_se = sd(Sepal.Length)/sqrt(n()),
    y_se = sd(Petal.Length)/sqrt(n())
  ) -> iris_mean
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
  geom_point(alpha = 0.5) +
  geom_errorbar(data = iris_mean, aes(ymin = y - y_se, ymax = y + y_se), width = 0, size = 1.2) +
  geom_errorbarh(data = iris_mean, aes(xmin = x - x_se, xmax = x + x_se), height = 0, size = 1.2)

如果需要十字和分组颜色区分,单独给误差棒设置color = "black"即可。

内容的提问来源于stack exchange,提问作者Daniel Fortin Guichard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 09:06:04