使用 geom_density 将密度曲线缩放到与 geom_histogram 相似的高度?

问题描述

我需要将密度线与 geom_histogram 的高度对齐,并在 y 轴上保持计数值而不是密度。

我有这两个版本:

#  Creating dataframe
library(ggplot2)

values <- c(rep(0,2),rep(2,3),rep(3,rep(4,5,rep(6,8,9,rep(11,2))
data_to_plot <- as.data.frame(values)

# Option 1 ( y scale shows frequency,but geom_density line and geom_histogram are not matching )
ggplot(data_to_plot,aes(x = values)) +
  geom_histogram(aes(y = ..count..),binwidth = 1,colour= "black",fill = "white") +
  geom_density(aes(y=..count..),fill="blue",alpha = .2)+
  scale_x_continuous(breaks = seq(0,max(data_to_plot$values),1))

y 比例显示频率,但 geom_密度线和 geom_histogram 不匹配

y scale shows frequency,but geom_density line and geom_histogram are not matching

# Option 2 (geom_density line and geom_histogram are matching,but y scale density = 1)

ggplot(data_to_plot,aes(x = values)) +
  geom_histogram(aes(y = after_stat(ndensity)),fill = "white") +
  geom_density(aes(y = after_stat(ndensity)),1))

geom_density 线和 geom_histogram 匹配,但 y 比例密度 = 1

geom_density line and geom_histogram are matching,but y scale density = 1

我需要的是选项 2 中的绘图,但选项 1 中的 Y 比例。我可以通过为此特定数据添加 (aes(y=1.25*..count..) 来获得它,但我的数据不是静态的,这不适用于其他数据集(只需修改 values 即可测试):

# Option 3 (with coefficient in aes())
ggplot(data_to_plot,fill = "white") +
  geom_density(aes(y=1.25*..count..),1))

预期结果:y 比例显示频率,geom_密度线与 geom_histogram 高度匹配

Desired result: y scale shows frequency and geom_density line is matching with geom_histogram height

我无法对系数或 bin 进行硬编码。 这个问题与这里讨论的问题很接近,但它对我的情况不起作用:

Programatically scale density curve made with geom_density to similar height to geom_histogram?

How to put geom_density and geom_histogram on same counts scale

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)