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

时间:2015-12-04 20:25:22

标签: r ggplot2 histogram normal-distribution

当我尝试用基础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中的酒吧与基础R不同,怎么样? *如何在ggplot2

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

1 个答案:

答案 0 :(得分:0)

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

添加正常情节