【发布时间】:2021-04-14 06:58:17
【问题描述】:
我需要将密度线与 geom_histogram 的高度对齐,并将计数值保持在 y 轴上而不是密度上。
我有这两个版本:
# Creating dataframe
library(ggplot2)
values <- c(rep(0,2), rep(2,3), rep(3,3), rep(4,3), 5, rep(6,2), 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_density 线和 geom_histogram 不匹配
# 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)), binwidth = 1, colour= "black", fill = "white") +
geom_density(aes(y = after_stat(ndensity)), fill="blue", alpha = .2)+
scale_x_continuous(breaks = seq(0, max(data_to_plot$values), 1))
geom_density 线和 geom_histogram 是匹配的,但是 y 比例密度 = 1
我需要的是选项 2 中的绘图,但选项 1 中的 Y 比例尺。我可以通过为此特定数据添加 (aes(y=1.25*..count..) 来获得它,但我的数据不是静态的,这不适用于另一个数据集(只需修改values 测试):
# Option 3 (with coefficient in aes())
ggplot(data_to_plot, aes(x = values)) +
geom_histogram(aes(y = ..count..), binwidth = 1, colour= "black", fill = "white") +
geom_density(aes(y=1.25*..count..), fill="blue", alpha = .2)+
scale_x_continuous(breaks = seq(0, max(data_to_plot$values), 1))
期望的结果:y 比例显示频率和 geom_density 线与 geom_histogram 高度匹配
我无法对系数或 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
【问题讨论】:
-
我理解您想要的结果,但我强烈反对。由于密度曲线的积分应该等于给定间隔的计数,因此将其提升到最大计数会在其他箱的间隔中证伪这一假设。
-
谢谢@c0bra,我明白你的意思了。
标签: r ggplot2 histogram curve density-plot