如何使用ggplot制作具有正态分布的分组直方图?

How to make a grouped histogram with normal distributions with ggplot?

当我尝试使用 base R 和 ggplot 制作一些分组直方图时,我找到了不同的解决方案。有人可以帮我找到问题所在。我猜它与 y 轴有关。

首先我创建了一些子集

Immature2=subset(dataHistogram2, Sex=='I')
Female2=subset(dataHistogram2, Sex=='F')
Male2=subset(dataHistogram2, Sex=='M')

带底座R

hist(Immature2$Diameter, prob=TRUE ,breaks= seq(55,125, by=5), ylim=c(0,0.05), xlim=c(55,125), col=rgb(0,1,0,1/2), main="", xlab= "Diameter", ylab="Densiteit")
hist(Female2$Diameter, prob=TRUE, add=TRUE, breaks= seq(55,125, by=5), col=rgb(1,0,0,1/2))
hist(Male2$Diameter, prob= T,breaks=seq(55,125, by=5), add=T, col=rgb(0,0,1,1/2))
x=seq(55,125,0.01)
curveImmature2<-curve(dnorm(x,mean=mean(Immature2$Diam), sd=sd(Immature2$Diam)), add= TRUE, col=rgb(0,1,0,1/2), lwd=2)
curveFemale2 <- curve(dnorm(x,mean=mean(Female2$Diam), sd=sd(Female2$Diam)), add= TRUE, col= rgb(1,0,0,1/2), lwd=2)
curveMale2 <- curve(dnorm(x, mean=mean(Male2$Diam), sd=sd(Male2$Diam)), add= TRUE, col=rgb(0,0,1,1/2), lwd=2)

enter image description here

使用ggplot

ggplot(dataHistogram2, aes(x=Diameter))+ geom_histogram(binwidth=5, aes(y=..density.., colour=Sex, fill= Sex), position="identity", alpha=0.5)+xlim(55,125) 

enter image description here

所以我的问题是: *为什么我的 ggplot 中的条形图与 base R 不同? *如何在 ggplot2

的直方图上按正态分布绘制不同的子集

可以用+ stat_function(fun=dnorm, colour = "red", args=list(mean=mean(Immature2$Diam), sd=sd(Immature2$Diam)))

添加一个正常的情节