r - 使用 ggplot 在直方图上绘制不同的分布

标签 r ggplot2 histogram curve density-plot

我试图在 R 中绘制直方图并用不同分布的密度覆盖它。它适用于常规直方图,但我无法让它与 ggplot2 包一起使用。

a <- dataset$age

现在遵循我的常规直方图的代码:

Histogram_for_age <- hist(a, prob=T, xlim=c(0,80), ylim=c(0,0.055), main="Histogram for age with density lines", xlab="age") 

mean <- mean(a)
sd <- sd(a)

现在是密度的直线/曲线:

lines(density(dataset$age), col="blue", lwd=2, lty=1)
curve(dnorm(x, mean = mean, sd = sd), add = T, col="red", lwd=2, lty=2)
curve(dgamma(x, shape =mean^2/sd^2, scale = sd^2/mean), add = T, col="goldenrod", lwd=2, lty=3) 

还有一个传说:

legend("topright", 
    c("actual distribution of age","gaussian distribution", "gamma distribution"),  
   lty=c(1,2,3),  
   lwd=c(2,2,2),col=c("blue","red","goldenrod"), cex=0.65) 

这是我到目前为止对 ggplot2 的尝试:

ggplot(dataset, aes(x=age)) + 
geom_histogram(aes(y=..density..),
             colour="black", fill="white") +
geom_density(alpha=.2, fill="lightblue") + stat_function(fun = dgamma, shape=shape)

哪个 ggplot2 参数等同于我的 lines() 和 curve() 参数?

最佳答案

像这样使用 stat_density 而不是 geom_density:

ggplot(dataset, aes(x=age)) + 
  geom_histogram(aes(y=..density..), colour="black", fill="white") +
  stat_density(colour="blue", geom="line", position="identity") +
  stat_function(fun=dnorm, args=list(mean=mean(dataset_with_victims$TV_Alter), sd=sd(dataset_with_victims$TV_Alter))) + 
  stat_function(fun=dgamma, args=list(shape=mean(dataset_with_victims$TV_Alter)^2/sd(dataset_with_victims$TV_Alter)^2, scale=sd(dataset_with_victims$TV_Alter)^2/mean(dataset_with_victims$TV_Alter)))

关于r - 使用 ggplot 在直方图上绘制不同的分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23335213/

相关文章:

R data.table : Difference between nested regressions results

r - 即使指定,散点图填充在 ggplot2 中也不会改变

r - 如何在 ggplot 中有效地按比例重新排序因子?

image-processing - 我怎样才能在直方图的基础上找到一个好的图像

r - 如何从数据框中的多列中找到最频繁的值

r - 使用TTR包计算指数移动平均线

相当于 R 函数 sweep() 的 Python numpy 或 pandas

r - ggplot2 中 facet_grid 的虚线

c++ - 如何从二维数据生成 OpenCV 一维直方图?

python - 如何在包含多个 matplotlib 直方图的一个图中设置 x 轴的边界并仅创建一列图表?