Plotting a normal distribution curve over a histogram

Flint

New Member
#1
I'm trying to plot a normal distribution curve over my histogram but I can't get my code to work for the curve. It just looks like it's plotting a very low curve, what am I doing wrong? This is my code:



minutes<-c(107, 116, 127, 126, 111, 90, 125, 124, 92, 121, 131, 137, 95, 101, 101, 111, 120, 114, 98, 106, 118, 82, 110, 115, 107, 121, 99, 100, 87)

m<-mean(minutes)
std<-sqrt(var(minutes))

hist(minutes,breaks=10,xlab="....",
main="Histogram of ....")

curve(dnorm(x, mean=m, sd=std),
col="darkblue", lwd=2, add=TRUE)
 

trinker

ggplot2orBust
#2
Here's my tried and true approach for this task:

Code:
minutes<-c(107, 116, 127, 126, 111, 90, 125, 124, 92, 121, 131, 137, 95, 101, 101, 111, 120, 114, 98, 106, 118, 82, 110, 115, 107, 121, 99, 100, 87) 

h <- hist(minutes,breaks=10,xlab="....", main="Histogram of ....")

xfit<-seq(min(minutes),max(minutes),length=40) 
yfit<-dnorm(xfit,mean=mean(minutes),sd=sd(minutes)) 
yfit <- yfit*diff(h$mids[1:2])*length(minutes) 
lines(xfit, yfit, col="red", lwd=2)


Or in ggplot2 (For the beloved TE):

Code:
dat <-data.frame(minutes=c(107, 116, 127, 126, 111, 90, 125, 124, 92, 121, 
    131, 137, 95, 101, 101, 111, 120, 114, 98, 106, 118, 82, 110, 115, 
    107, 121, 99, 100, 87))

ggplot(dat, aes(x=minutes)) +
    geom_histogram(aes(y=..density..), binwidth=4.5) + 
    geom_density(fill=NA, colour="blue")
 

Dason

Ambassador to the humans
#3
I personally just use the prob=TRUE parameter in the histogram call if I want to plot a normal curve over it and then use the 'curve' function with add=TRUE.

Code:
y <- rnorm(20)
hist(y, prob = TRUE)
curve(dnorm(x, mean(y), sd(y)), add = TRUE)
 

trinker

ggplot2orBust
#4
Or...

Code:
library(lessR)
Density(minutes, data=dat,)
PS didn't know you could do that Dason. I have always used peter dalgaard's approach above.