Can't fit a normal curve to a grouped histogram

岁酱吖の 提交于 2019-11-28 11:34:41

问题


I'm struggling with an assignment I was given. We have to make a grouped histogram with normal fit superimposed. Now, I already managed to get de grouped histogram in Basic R graph, Lattice and Ggplot. In Basic R graph, I was also able to get an normal curve in it, but in Lattice and Ggplot I seem to fail in doing so.

Here is my R script from Lattice and Ggplot:

#Lattice:
library(lattice)
histogram(~SBP, data= DataSBP, breaks=10,
          type=c("density"), 
          groups = User, panel = function(...)panel.superpose(...,panel.groups=panel.histogram, col=c("navy","maroon3"),alpha=0.4),
          auto.key=list(columns=2,rectangles=FALSE, col=c("navy","maroon3")))
panel.mathdensity(dmath=dnorm, col="black", args=list(mean=mean(x, na.rm = TRUE), sd=sd(x, na.rm = TRUE)))

When I try the command "panel.mathdensity" nothing happens.

# Ggplot
library(ggplot2)
ggplot(DataSBP, aes(x=SBP)) + geom_histogram(aes(y=..density.., x=SBP, colour=User, fill=User),alpha=0.5, binwidth = 5, position="identity")
+ stat_function(fun = dnorm, args = list(mean = SBP.mean, sd = SBP.sd))

If I try the stat_function command, I always get the error "SBP.mean" can't be found, which probably means I have to define SBP.mean, but how?

My data is like this:

User SBP    
No 102    
No 116    
No 106    
...    
Yes 117    
Yes 127    
Yes 111    
...

And my graphs look like this:


回答1:


Were you looking for something like this? I don't have access to your dataset so I used the iris dataset

library(dplyr); library(ggplot2)

meanSe <- iris %>% 
  filter(Species == "setosa") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVe <- iris %>% 
  filter(Species == "versicolor") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVi <- iris %>% 
  filter(Species == "virginica") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
ggplot(iris, aes(x=Sepal.Length, color=Species, fill=Species)) +
  geom_histogram(aes(y=..density..), position="identity", binwidth=.5) + 
  stat_function(fun = dnorm, color="red", args=list(mean=meanSe$means, sd=meanSe$sd)) + 
  stat_function(fun = dnorm, color="green", args=list(mean=meanVe$means, sd=meanVe$sd)) + 
  stat_function(fun = dnorm, color="blue", args=list(mean=meanVi$means, sd=meanVi$sd)) + 
  theme_bw()

give this



来源:https://stackoverflow.com/questions/34450341/cant-fit-a-normal-curve-to-a-grouped-histogram

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!