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

如何为geom_density分布图的自定义值及百分位数竖线添加标签

给ggplot2密度图的竖线添加自定义标签的解决方案

我来帮你搞定这个标签的问题!你现在的代码里标签位置不对主要是因为y值设成了0,而且没针对不同竖线的需求调整对齐方式。我给你优化一下代码,完全符合你想要的标签位置:

首先,咱们提前把需要用到的数值都算好,这样代码更清晰,也避免重复计算:

library(ggplot2)

# 提取自定义值和分位数
custom_val <- dataset$`Estimated percent body fat`[12]
q5_val <- quantile(dataset$`Estimated percent body fat`, 0.05, na.rm = TRUE)
q95_val <- quantile(dataset$`Estimated percent body fat`, 0.95, na.rm = TRUE)

# 计算密度曲线的最大y值,用来准确定位顶部标签
dens_curve <- density(dataset$`Estimated percent body fat`, na.rm = TRUE)
max_y <- max(dens_curve$y)

接下来是完整的绘图代码,咱们用annotate()来添加标签(比geom_text()更适合单个文本元素),同时调整对齐方式和位置:

ggplot(dataset, aes(x = `Estimated percent body fat`)) + 
  geom_density() + 
  # 绘制三条竖线,简化写法不用嵌套aes()
  geom_vline(xintercept = custom_val, color = "red", size = 1) + 
  geom_vline(xintercept = q5_val, color = "grey", size = 0.5) + 
  geom_vline(xintercept = q95_val, color = "grey", size = 0.5) + 
  # 添加自定义值标签:顶部右侧,左对齐(hjust=0)让标签在竖线右边
  annotate("text", x = custom_val, y = max_y * 1.05, label = "Custom", 
           color = "red", hjust = 0) +
  # 5%分位数标签:中部左侧,右对齐(hjust=1)让标签在竖线左边
  annotate("text", x = q5_val, y = max_y / 2, label = "5th Percentile", 
           color = "grey", hjust = 1) +
  # 95%分位数标签:中部右侧,左对齐让标签在竖线右边
  annotate("text", x = q95_val, y = max_y / 2, label = "95th Percentile", 
           color = "grey", hjust = 0) +
  # 调整图表边距,防止顶部标签被裁剪
  theme(plot.margin = margin(10, 10, 10, 10))

关键调整说明:

  • 提前计算数值:把自定义值、分位数和密度最大值都先算好,代码更简洁,后续调整也更方便。
  • 用annotate()添加标签:这类单个的文本元素不需要映射到数据框的行,annotate()比geom_text()更合适,不用纠结aes里的参数。
  • hjust对齐参数:hjust=0是左对齐,标签会出现在竖线右侧;hjust=1是右对齐,标签会出现在竖线左侧,完美匹配你的位置需求。
  • 动态定位y值:用密度曲线的最大值来计算标签位置,不管数据怎么变化,标签都能刚好在曲线顶部上方,不会跑偏;中部标签用最大值的一半,刚好在图表中间位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:52:58