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

如何在ggplot直方图的最高分箱处添加geom_vline竖线?

解决方法

要在直方图的最高分箱位置添加竖线,关键是找到频数最高的分箱对应的x轴位置,而非x的最大值。可以通过after_stat()获取分箱的统计数据,定位到频数最大的分箱中点:

library(ggplot2)

set.seed(15)
df <- data.frame(x=rnorm(100,5,2))

df |> 
  ggplot(aes(x=x))+ 
  geom_histogram(binwidth = 1, fill = "lightblue", color = "black") +
  stat_bin(geom = "vline", 
           aes(xintercept = after_stat(x[which.max(count)])), 
           binwidth = 1, 
           color = "red", 
           linetype = "dashed",
           size = 1)

代码说明

  • after_stat(count):获取每个分箱的频数(y值)
  • x[which.max(count)]:找到频数最大的分箱对应的x轴中点位置,以此作为竖线的截距
  • 保持binwidth = 1和直方图一致,确保分箱规则统一,避免位置偏差

这样就能精准在最高分箱的中心位置添加竖线,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:14:54