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

如何在stat_summary()+after_stat()绘制的直方图上整齐放置geom_text标签

解决分面直方图添加均值/中位数标签并对齐的问题

要让均值和中位数标签在每个分面左上角整齐对齐,核心是通过stat_summary()固定标签位置,结合after_stat()提取统计量,再用对齐参数调整位置。

修改后的完整代码

library(dplyr, warn.conflicts = FALSE)
library(ggplot2)

diamonds |> 
  filter(color %in% c("D", "E", "F") & cut %in% c("Very Good", "Premium")) |> 
  ggplot(aes(x = depth)) +
  geom_histogram(binwidth = 0.5) + # 指定binwidth消除默认提示
  # 添加均值标签
  stat_summary(
    fun = mean,
    geom = "text",
    aes(label = paste0("均值: ", round(after_stat(y), 2))),
    x = -Inf, y = Inf, # 定位到分面左上角区域
    hjust = -0.1, vjust = 1.2, # 微调避免贴边
    size = 3.5
  ) +
  # 添加中位数标签
  stat_summary(
    fun = median,
    geom = "text",
    aes(label = paste0("中位数: ", round(after_stat(y), 2))),
    x = -Inf, y = Inf,
    hjust = -0.1, vjust = 2.5, # 让标签在均值下方排列
    size = 3.5
  ) +
  facet_grid(cut ~ color)

关键细节说明

  • 用x = -Inf和y = Inf自动适配每个分面的坐标轴范围,将标签固定到左上角区域
  • 通过hjust(水平对齐)和vjust(垂直对齐)微调标签位置,避免与边框或直方图柱子重叠
  • after_stat(y)直接提取stat_summary()计算出的均值/中位数数值,round()控制小数位数
  • 手动设置binwidth可消除原代码的默认提示信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:25:59