title: Adding a density line to a histogram with count data in ggplot2
body: <p>I want to add a density line (a normal density actually) to a histogram. </p>
  
  <p>Suppose I have the following data. I can plot the histogram by <code>ggplot2</code>:</p>
  
  <pre><code>set.seed(123)    
  df &lt;- data.frame(x = rbeta(10000, shape1 = 2, shape2 = 4))
  
  ggplot(df, aes(x = x)) + geom_histogram(colour = "black", fill = "white", 
                                          binwidth = 0.01) 
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/SFO1C.png" alt="enter image description here"></p>
  
  <p>I can add a density line using:</p>
  
  <pre><code>ggplot(df, aes(x = x)) + 
    geom_histogram(aes(y = ..density..),colour = "black", fill = "white", 
                   binwidth = 0.01) + 
    stat_function(fun = dnorm, args = list(mean = mean(df$x), sd = sd(df$x)))
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/704LO.png" alt="enter image description here"></p>
  
  <p>But this is not what I actually want, I want this density line to be fitted to the count data. </p>
  
  <p>I found a similar post (<a href="http://r.789695.n4.nabble.com/Howto-fit-normal-curve-into-histogram-using-GGPLOT2-tc898609.html#a898611" rel="noreferrer">HERE</a>) that offered a solution to this problem. But it did not work in my case. I need to an arbitrary expansion factor to get what I want. And this is not generalizable at all:</p>
  
  <pre><code>ef &lt;- 100 # Expansion factor
  
  ggplot(df, aes(x = x)) + 
    geom_histogram(colour = "black", fill = "white", binwidth = 0.01) + 
    stat_function(fun = function(x, mean, sd, n){ 
      n * dnorm(x = x, mean = mean, sd = sd)}, 
      args = list(mean = mean(df$x), sd = sd(df$x), n = ef))
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/0Gun1.png" alt="enter image description here"></p>
  
  <p>Any clues that I can use to generalize this </p>
  
  <ul>
  <li>first to normal distribution, </li>
  <li>then to any other bin size, </li>
  <li>and lastly to any other distribution will be very helpful.</li>
  </ul>