简体   繁体   中英

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

When I tried to make some grouped histograms with base R and ggplot, I have found a different solution. Can someone help me to find the problem. I guess it is something with the y -axis.

First I created some subsets

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

With base 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

With 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

So my questions: *How does it come that my bars in my ggplot are different from base R? *How can I plot my different subsets in an normal distribution on the histogram on ggplot2

可以使用+ stat_function(fun=dnorm, colour = "red", args=list(mean=mean(Immature2$Diam), sd=sd(Immature2$Diam)))添加一个法线图+ stat_function(fun=dnorm, colour = "red", args=list(mean=mean(Immature2$Diam), sd=sd(Immature2$Diam)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM