【发布时间】:2020-04-15 09:15:31
【问题描述】:
我是 R 编程语言的新手。使用 ggplot2 在直方图上叠加密度曲线的标准/通用方法是什么?
【问题讨论】:
我是 R 编程语言的新手。使用 ggplot2 在直方图上叠加密度曲线的标准/通用方法是什么?
【问题讨论】:
这取决于您是需要经验密度估计还是拟合理论密度。在这两种情况下,您都需要将直方图箱的宽度与密度相匹配。
对于经验核密度估计:
library(ggplot2)
# dummy data
df <- data.frame(
x = rnorm(1000)
)
binwidth <- 0.1
ggplot(df, aes(x)) +
geom_histogram(binwidth = binwidth) +
geom_density(aes(y = after_stat(count * binwidth)),
color = "red")
理论密度估计并不存在于 ggplot2 中,而是存在于扩展包中。免责声明:我是以下包的作者,所以我有偏见:
library(ggh4x)
ggplot(df, aes(x)) +
geom_histogram(binwidth = binwidth) +
stat_theodensity(aes(y = after_stat(count * binwidth)),
color = "red")
或者,如果您不想设置 binwidths,您也可以将直方图缩放为密度:
ggplot(df, aes(x)) +
geom_histogram(aes(y = after_stat(density))) +
geom_density(color = "red")
注意:after_stat() 需要 ggplot2 v3.3.0,早期版本使用stat()。
【讨论】:
binwidth 是一个变量,您会事先分配给自己,例如在我的答案的第一个代码块中。
您需要确保将密度图调用中 ..count.. 的值乘以直方图调用中 binwidth 的值。
你可以这样做:
set.seed(100)
a = data.frame(z = rnorm(10000))
binwidthVal=0.1
ggplot(a, aes(x=z)) +
geom_histogram(binwidth = binwidthVal) +
geom_density(colour='red', aes(y=binwidthVal * ..count..))
Credit to Brian Diggs for the idea.
编辑:似乎已经有一个非常好的答案here
【讨论】: