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

如何使用geom_boxplot绘制中线为均值而非中位数的箱线图?

解决箱线图中线替换为均值的问题

嘿,我刚好碰到过一样的需求!要把箱线图的中线从默认的中位数改成均值,用ggplot2有两种靠谱的办法,帮你一步步搞定:

方法1:隐藏原中位数线,添加均值作为中线

这种方法保留箱线图的四分位数、须线等原有结构,只是把中间的线替换成均值,非常直观:

首先先把你的数据整理成完整的数据框(我补全了wind向量的缺失部分,你可以根据实际情况调整):

dust <- c(4.5, 3.7, 5, 5.2, 8.5, 6.6, 4.7, 5, 5.7, 4.3, 2.3, 7.6, 5.2, 6, 8.7, 7.5, 7.7, 11, 9, 6.5, 8.7, 5, 2.2, 7.5, 7.5, 3.5)
wind <- c("Present", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Present", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Absent", "Present", "Absent", "Absent", "Absent")
df <- data.frame(dust, wind)

然后绘制箱线图:

library(ggplot2)

ggplot(df, aes(x = wind, y = dust)) +
  # 绘制箱线图,设置median.color=NA隐藏默认的中位数线
  geom_boxplot(color = "black", fill = "lightblue", outlier.color = "red", median.color = NA) +
  # 添加均值作为中线,group参数确保每个分组都画一条线
  stat_summary(fun = mean, geom = "line", aes(group = wind), color = "black", linewidth = 1) +
  # 可选:添加白色均值点,让中线更醒目
  stat_summary(fun = mean, geom = "point", color = "white", size = 2) +
  labs(title = "箱线图(中线为均值)", x = "风况", y = "粉尘浓度")

方法2:自定义箱线统计量,直接替换中线为均值

如果你想让箱线图的统计逻辑里直接用均值作为中线,可以自定义统计函数,覆盖默认的箱线计算规则:

# 自定义箱线统计函数:把中位数替换成均值
custom_box_stats <- function(y) {
  # 获取默认箱线统计量(顺序:最小值、下四分位、中位数、上四分位、最大值)
  default_stats <- boxplot.stats(y)$stats
  # 将中位数位置(第3个元素)替换为均值
  default_stats[3] <- mean(y, na.rm = TRUE)
  return(default_stats)
}

# 绘制自定义箱线图
ggplot(df, aes(x = wind, y = dust)) +
  stat_boxplot(fun.data = custom_box_stats, geom = "boxplot", color = "black", fill = "lightblue") +
  labs(title = "箱线图(中线为均值)", x = "风况", y = "粉尘浓度")

为什么stat_smooth没用?

你之前尝试的stat_smooth是用来拟合数据趋势线的(比如线性回归曲线、局部平滑曲线),和箱线图的中线完全不是一个功能,所以没效果是正常的哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:59:24