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

4

我试图在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()参数?

1个回答

7

使用 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)))

谢谢您的快速回复!关于我上面的伽马规格,我应该使用什么形状参数? - Cajira
你可能需要添加 geom="point" 然后定义形状。你能提供一些示例数据吗?这样我就可以更容易地给出适当的答案了。 - Jaap
1
@Cajira可能是指dgamma函数中的shape参数。您应该在stat_function()调用中添加arg=list(shape=...) - ilir
@ilir 谢谢,我已经将它包含在我的答案中。 - Jaap
谢谢!!! :) 我现在还有问题。使用您上面的代码,R返回以下内容:stat_bin: binwidth默认为range/30。使用'binwidth = x'来调整它。 - Cajira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接