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

如何使用ggplot的stat_summary函数绘制方差图

用stat_summary绘制方差相关图形的解决方案

首先,将你提供的数据集转为可直接运行的R代码:

Data <- data.frame(
  Sample = factor(c(rep(1,6), rep(2,5))),
  temp = c(6.9, 6.8, 5.5, 3.6, 2.5, 2.3, 2.8, 13.4, 19, 18.7, 20)
)

两种常见的方差可视化场景:

1. 直接展示各组的方差值

如果想直观显示每个Sample组的方差大小,适合用点或柱状图这类单值geom(errorbar是误差棒,不适合展示单个数值):

library(ggplot2)
ggplot(Data, aes(x = Sample, y = temp)) +
  stat_summary(geom = "point", fun = "var", size = 3, color = "darkred") +
  labs(title = "各组温度的方差", y = "方差值")

2. 绘制均值±方差的误差棒

这是更常用的误差棒用法——以组均值为中心,上下延伸方差的范围。此时需要给stat_summary提供误差棒的上下限,有两种实现方式:

方式一:自定义fun.data函数

# 定义函数,返回均值、均值-方差、均值+方差
mean_with_var <- function(x) {
  avg <- mean(x)
  var_val <- var(x)
  data.frame(y = avg, ymin = avg - var_val, ymax = avg + var_val)
}

ggplot(Data, aes(x = Sample, y = temp)) +
  stat_summary(geom = "point", fun = "mean", size = 3) + # 绘制均值点
  stat_summary(geom = "errorbar", fun.data = mean_with_var, width = 0.2) + # 误差棒
  labs(title = "温度均值±方差", y = "温度")

方式二:直接指定fun.min和fun.max

ggplot(Data, aes(x = Sample, y = temp)) +
  stat_summary(geom = "point", fun = "mean", size = 3) +
  stat_summary(geom = "errorbar",
               fun = "mean", # 中心值用均值
               fun.min = function(x) mean(x) - var(x), # 下限:均值-方差
               fun.max = function(x) mean(x) + var(x), # 上限:均值+方差
               width = 0.2) +
  labs(title = "温度均值±方差", y = "温度")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:54:52