title: using stat_function and facet_wrap together in ggplot2 in R
body: <p>I am trying to plot lattice type data with ggplot2 and then superimpose a normal distribution over the sample data to illustrate how far off normal the underlying data is. I would like to have the normal dist on top to have the same mean and stdev as the panel. </p>
  
  <p>here's an example:</p>
  
  <pre><code>library(ggplot2)
  
  #make some example data
  dd&lt;-data.frame(matrix(rnorm(144, mean=2, sd=2),72,2),c(rep("A",24),rep("B",24),rep("C",24)))
  colnames(dd) &lt;- c("x_value", "Predicted_value",  "State_CD")
  
  #This works
  pg &lt;- ggplot(dd) + geom_density(aes(x=Predicted_value)) +  facet_wrap(~State_CD)
  print(pg)
  </code></pre>
  
  <p>That all works great and produces a nice three panel graph of the data. How do I add the normal dist on top? It seems I would use stat_function, but this fails:</p>
  
  <pre><code>#this fails
  pg &lt;- ggplot(dd) + geom_density(aes(x=Predicted_value)) + stat_function(fun=dnorm) +  facet_wrap(~State_CD)
  print(pg)
  </code></pre>
  
  <p>It appears that the stat_function is not getting along with the facet_wrap feature. How do I get these two to play nicely?</p>
  
  <p><strong>------------EDIT---------</strong></p>
  
  <p>I tried to integrate ideas from two of the answers below and I am still not there:</p>
  
  <p>using a combination of both answers I can hack together this:</p>
  
  <pre><code>library(ggplot)
  library(plyr)
  
  #make some example data
  dd&lt;-data.frame(matrix(rnorm(108, mean=2, sd=2),36,2),c(rep("A",24),rep("B",24),rep("C",24)))
  colnames(dd) &lt;- c("x_value", "Predicted_value",  "State_CD")
  
  DevMeanSt &lt;- ddply(dd, c("State_CD"), function(df)mean(df$Predicted_value)) 
  colnames(DevMeanSt) &lt;- c("State_CD", "mean")
  DevSdSt &lt;- ddply(dd, c("State_CD"), function(df)sd(df$Predicted_value) )
  colnames(DevSdSt) &lt;- c("State_CD", "sd")
  DevStatsSt &lt;- merge(DevMeanSt, DevSdSt)
  
  pg &lt;- ggplot(dd, aes(x=Predicted_value))
  pg &lt;- pg + geom_density()
  pg &lt;- pg + stat_function(fun=dnorm, colour='red', args=list(mean=DevStatsSt$mean, sd=DevStatsSt$sd))
  pg &lt;- pg + facet_wrap(~State_CD)
  print(pg)
  </code></pre>
  
  <p>which is really close... except something is wrong with the normal dist plotting:</p>
  
  <p><a href="https://i.stack.imgur.com/g9SEX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g9SEX.png" alt="enter image description here"></a></p>
  
  <p>what am I doing wrong here?</p>