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

如何为R ggplot2百分比直方图添加匹配刻度的密度曲线

问题解决方法

出现刻度不匹配的核心原因是geom_density()默认输出的核密度估计值积分总和为1,和你手动计算的百分比Y轴(数值范围通常为0~100)量级不匹配,只要对密度曲线的Y轴数值做同等缩放即可。

兼容旧版ggplot2的写法

library(ggplot2)
df <- data.frame(V1 = rnorm(100))
ggplot(df, aes(x = V1)) +  
  # 直方图Y轴为百分比,可自行调整binwidth适配数据分布
  geom_histogram(aes(y = 100*(..count..)/sum(..count..)), binwidth = 0.3, fill = "lightblue", color = "black") +
  # 密度曲线乘以100匹配百分比刻度
  geom_density(aes(y = 100 * ..density..), color = "red", linewidth = 1) +
  labs(y = "百分比(%)", x = "V1")

新版ggplot2(v3.3.0及以上)推荐写法

使用after_stat()替代已不推荐的双点语法,规范度更高:

library(ggplot2)
df <- data.frame(V1 = rnorm(100))
ggplot(df, aes(x = V1)) +  
  geom_histogram(aes(y = after_stat(100 * count / sum(count))), binwidth = 0.3, fill = "lightblue", color = "black") +
  geom_density(aes(y = after_stat(100 * density)), color = "red", linewidth = 1) +
  labs(y = "百分比(%)", x = "V1")

如果觉得密度曲线和直方图贴合度不符合预期,可以调整geom_density()的bw参数修改核密度带宽:数值越小曲线越贴合原始数据波动,数值越大曲线越平滑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:30:05