title: R - Smoothing color and adding a legend to a scatterplot
body: <p>I have a scatterplot in R. Each <code>(x,y)</code> point is colored according to its <code>z</code> value. So you can think of each point as <code>(x,y,z)</code>, where <code>(x,y)</code> determines its position and <code>z</code> determines its color along a color gradient. I would like to add two things</p>
  
  <ol>
  <li>A legend on the right side showing the color gradient and what <code>z</code> values correspond to what colors</li>
  <li>I would like to smooth all the color using some type of interpolation, I assume. In other words, the entire plotting region (or at least most of it) should become colored so that it looks like a huge heatmap instead of a scatterplot. So, in the example below, there would be lots of orange/yellow around and then some patches of purple throughout. I'm happy to further clarify what I'm trying to explain here, if need be.</li>
  </ol>
  
  <p>Here is the code I have currently, and the image it makes.</p>
  
  <pre><code>x &lt;- seq(1,150)
  y &lt;- runif(150)
  z &lt;- c(rnorm(mean=1,100),rnorm(mean=20,50))
  colorFunction &lt;- colorRamp(rainbow(100))
  zScaled &lt;- (z - min(z)) / (max(z) - min(z))
  zMatrix &lt;- colorFunction(zScaled)
  zColors &lt;- rgb(zMatrix[,1], zMatrix[,2], zMatrix[,3], maxColorValue=255)
  df &lt;- data.frame(x,y)
  x &lt;- densCols(x,y, colramp=colorRampPalette(c("black", "white")))
  df$dens &lt;- col2rgb(x)[1,] + 1L
  plot(y~x, data=df[order(df$dens),],pch=20, col=zColors, cex=1)
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/jhIJL.png" alt="enter image description here"></p>