title: How does ggplot2 density differ from the density function?
body: <p>Why do the following plots look different? Both methods appear to use Gaussian kernels.</p>
  
  <p>How does <code>ggplot2</code> compute a density?</p>
  
  <pre><code>library(fueleconomy)
  
  d &lt;- density(vehicles$cty, n=2000)
  ggplot(NULL, aes(x=d$x, y=d$y)) + geom_line() + scale_x_log10()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/kwYX9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwYX9.png" alt="enter image description here"></a></p>
  
  <pre><code>ggplot(vehicles, aes(x=cty)) + geom_density() + scale_x_log10()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Up5yP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Up5yP.png" alt="enter image description here"></a></p>
  
  <hr>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>A solution to this question already appears on SO <a href="https://stackoverflow.com/questions/18162425/the-difference-between-geom-density-in-ggplot2-and-density-in-base-r">here</a>, however the specific parameters ggplot2 is passing to the R stats density function remain unclear.</p>
  
  <p>An alternate solution is to extract the density data straight from the ggplot2 plot, as shown <a href="https://stackoverflow.com/questions/12394321/r-what-algorithm-does-geom-density-use-and-how-to-extract-points-equation-of">here</a></p>