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

如何在ggplot2绘图中添加按分面实时计算均值的标注

按分面添加实时计算的均值标注(ggplot2)

核心思路是借助stat="summary"让ggplot自动按分面分组计算均值,无需提前将均值存入变量,直接在绘图代码里完成标注添加。

先给你一个包含基础直方图、均值竖线的示例代码作为参照:

library(ggplot2)

ggplot(diamonds, aes(x = carat)) +
  geom_histogram(binwidth = 0.1, fill = "#69b3a2", alpha = 0.7) +
  geom_vline(stat = "summary", fun = mean, color = "red", linetype = "dashed") +
  facet_wrap(~cut)

要添加分面的均值标注,直接新增geom_text()层即可,具体代码如下:

library(ggplot2)

ggplot(diamonds, aes(x = carat)) +
  geom_histogram(binwidth = 0.1, fill = "#69b3a2", alpha = 0.7) +
  geom_vline(stat = "summary", fun = mean, color = "red", linetype = "dashed") +
  # 新增的均值标注语句
  geom_text(
    stat = "summary",
    fun = mean,
    aes(label = paste0("Mean Carat = ", round(..x.., 2))),
    y = Inf,  # 把标注固定在分面顶部
    vjust = 1.2,  # 调整垂直位置避免和直方图顶边重叠
    color = "darkred",
    fontface = "bold"
  ) +
  facet_wrap(~cut)

关键细节说明

  • stat = "summary":让ggplot自动按分面(即cut分组)计算均值,不用提前用dplyr等工具预处理数据
  • ..x..:在aes()里引用统计计算后的均值结果(因为指定了fun=mean,所以..x..就是对应分面的carat均值)
  • round(..x.., 2):把均值保留两位小数,让标注更整洁易读
  • y = Inf和vjust = 1.2:将标注固定在分面顶部,避免被直方图柱子遮挡

如果想把标注放在均值竖线旁边(比如竖线右侧),可以调整位置参数:

geom_text(
  stat = "summary",
  fun = mean,
  aes(x = ..x.. + 0.1, label = paste0("Mean = ", round(..x.., 2))),
  y = 500,  # 固定y轴位置,可根据你的直方图高度调整
  color = "darkred",
  fontface = "bold"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:33:25