[R] Howto fit normal curve into histogram using GGPLOT2

John Kane jrkrideau at yahoo.ca
Wed Sep 2 17:40:14 CEST 2009


Crudely but I think it works

x <- data.frame(aa <- mtcars$mpg)
b <- ggplot(x, aes(aa)) + geom_histogram(aes(y=..density..)) + 
         stat_function(fun=dnorm, args=list(mean=mean(x$aa), sd=sd(x$aa)))
b


--- On Wed, 9/2/09, Gundala Viswanath <gundalav at gmail.com> wrote:

> From: Gundala Viswanath <gundalav at gmail.com>
> Subject: [R] Howto fit normal curve into histogram using GGPLOT2
> To: r-help at stat.math.ethz.ch
> Received: Wednesday, September 2, 2009, 10:36 AM
> Currently, I am doing it this way.
> 
> x <- mtcars$mpg
> h<-hist(x, breaks=10, col="red", xlab="Miles Per
> Gallon",
>    main="Histogram with Normal Curve")
> xfit<-seq(min(x),max(x),length=40)
> yfit<-dnorm(xfit,mean=mean(x),sd=sd(x))
> yfit <- yfit*diff(h$mids[1:2])*length(x)
> lines(xfit, yfit, col="blue", lwd=2)
> 
> But since, ggplot2  has more appealing graphics,
> I wonder how can it be done.
> 
> -G.V.
> 
> ______________________________________________
> R-help at r-project.org
> mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained,
> reproducible code.
> 


      __________________________________________________________________
Looking for the perfect gift? Give the gift of Flickr! 

http://www.flickr.com/gift/




More information about the R-help mailing list