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:
See Question&Answers more detail:
os