title: ggplot2 with gradient density fill?
body: <p>I have generated a ggplot2 graph and I want to fill it showing the density of the points. I have managed it using the following formula for density:</p>
  
  <pre><code>get_density &lt;- function(x, y, n = 250) {
    dens &lt;- MASS::kde2d(x = x, y = y, n = n)
    ix &lt;- findInterval(x, dens$x)
    iy &lt;- findInterval(y, dens$y)
    ii &lt;- cbind(ix, iy)
    return(dens$z[ii])}
  </code></pre>
  
  <p>and then getting the density of the points in a new "density" column based on the formula, with "lfc" and "pval" being the x,y variables:</p>
  
  <pre><code>data.MA$density &lt;- get_density(data.MA$pval, data.MA$lfc)
  </code></pre>
  
  <p>The ggplot object I am plotting is:</p>
  
  <pre><code>  heatmap2 &lt;- ggplot() + 
    geom_point(data = filter(data.MA, chg == "unchanged"), 
               aes(basemean, lfc, color = density)) + 
    geom_point(data = filter(data.MA, chg == "changed"), 
               aes(basemean, lfc, fill = dir), 
               shape = 21, size = 2, stroke = 0.1) +
    scale_fill_manual(values = c("#FFA600", "#00B2FF", "#00B2FF")) +
    scale_colour_gradient2(low = "blue", mid = "white", high = "red", midpoint = 10) +
    theme_bw() + scale_y_continuous() + scale_x_continuous()
  </code></pre>
  
  <p>This gives me the following graph:</p>
  
  <p><a href="https://i.stack.imgur.com/b08zm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b08zm.jpg" alt="MA plot gradient"></a></p>
  
  <p>Here is a samples of the data.MA:</p>
  
  <pre><code>gene     pval  lfc basemean      density       dir peakid     chg
  1    NXT1 41.22403 3.58     9.50 3.339690e-02 increased      1 changed
  2   BEND5 23.41567 5.03     8.01 0.000000e+00 increased      2 changed
  3    PLB1 23.19450 7.91     8.13 4.849746e-78 increased      3 changed
  4   LYRM9 20.81531 2.35    11.43 0.000000e+00 increased      4 changed
  5 MIR4464 14.73049 3.65     7.99 0.000000e+00 increased      5 changed
  6 HSD17B2 14.63451 4.51     7.31 0.000000e+00 increased      6 changed
  </code></pre>
  
  <p>My question is how can I make the gradient more disperse in the middle, so it is not just a red stripe in the middle and more of a gradient? </p>
  
  <p>Can anyone suggest a different formula for the density perhaps?</p>
  
  <p>Or a way to define the gradient better to be in more separate blocks?</p>