1

I use the following code to get two histograms from two vectors Model.1 and Model.2. I would like to have R fit a normal curve to each of the histograms.

library(ggplot2)

require(ggplot2)
require(reshape2)

set.seed(1)
df <- data.frame(x<-rnorm(1000,mean = 0.5, sd = 0.01),
                 y<-rnorm(1000,mean = 0.5, sd = 0.01))
df2 = melt(df)

ggplot(df2, aes(value, fill = variable)) + geom_histogram(position = "dodge", binwidth=0.001,colour = "black")+    scale_fill_manual(values = c('red','blue'))+
  facet_wrap(~variable, nrow=2)+theme_bw()+ scale_x_continuous(breaks=seq(0.45,0.540,1/200))+ geom_vline(xintercept = 0.5, colour="black") + 
  stat_function(fun=dnorm) 

Thanks.

marbel
  • 7,560
  • 6
  • 49
  • 68
Ku-trala
  • 651
  • 3
  • 9
  • 20
  • 1
    Can you give output of `dput(df2)` so that we can recreate data on our end? – CHP Jan 06 '14 at 03:24
  • 2
    this gets asked a lot. "fitting" a normal curve to a histogram just requires computing the sample mean and standard dev of the data (since these are provably good estimates of the true mean and standard dev). I guess you mean that you want the normal curves overlaid on the plot? – Ben Bolker Jan 06 '14 at 03:29
  • [This seems to be a good answer.](http://stackoverflow.com/questions/7182556/how-to-add-gaussian-curve-to-histogram-created-with-qplot) [Here is another good link:](http://stackoverflow.com/questions/1376967/using-stat-function-and-facet-wrap-together-in-ggplot2-in-r) – marbel Jan 06 '14 at 04:20
  • Hi, I added an example of how the data could look. Thanks. – Ku-trala Jan 06 '14 at 13:18

1 Answers1

2

Useful links:

With ggplot: How to add gaussian curve to histogram created with qplot?

using stat_function and facet_wrap together in GGPLOT2 in R

With Base graphics: Fitting a density curve to a histogram in R

Here is Andreis answer to the problem.

library(ggplot2)
data <- data.frame(V1 <- rnorm(700), V2=sample(LETTERS[1:7], 700, replace=TRUE))
ggplot(data, aes(x=V1)) + 
  stat_bin(aes(y=..density..)) + 
  stat_function(fun=dnorm) + 
  facet_grid(V2~.)

This is what i´ve been trying, but it´s not really working. Perhaps a ggplot2 expert could iluminate us. :)

ggplot(df2, aes(x = value)) + 
  stat_bin(aes(y =..density..)) + 
  stat_function(fun = dnorm) + 
  facet_grid(. ~ variable)


ggplot(data = df2, aes(x = value)) + 
  facet_wrap(~ variable) + 
  geom_histogram(aes(y = ..density..)) + 
  stat_function(fun = dnorm, colour = "blue")
Community
  • 1
  • 1
marbel
  • 7,560
  • 6
  • 49
  • 68
  • I can't seem to make this work with my current code and I already tried looking through the other question about fitting a normal distribution. How exactly does it look in my example? Thanks. – Ku-trala Jan 06 '14 at 11:19
  • @Ku-trala you have to be very specific about "doesn't work" so we can understand what you desire for a result and what you actually got. – Carl Witthoft Jan 06 '14 at 12:46