I have a scatterplot in R. Each (x,y)
point is colored according to its z
value. So you can think of each point as (x,y,z)
, where (x,y)
determines its position and z
determines its color along a color gradient. I would like to add two things
- A legend on the right side showing the color gradient and what
z
values correspond to what colors - 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.
Here is the code I have currently, and the image it makes.
x <- seq(1,150)
y <- runif(150)
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))
colorFunction <- colorRamp(rainbow(100))
zScaled <- (z - min(z)) / (max(z) - min(z))
zMatrix <- colorFunction(zScaled)
zColors <- rgb(zMatrix[,1], zMatrix[,2], zMatrix[,3], maxColorValue=255)
df <- data.frame(x,y)
x <- densCols(x,y, colramp=colorRampPalette(c("black", "white")))
df$dens <- col2rgb(x)[1,] + 1L
plot(y~x, data=df[order(df$dens),],pch=20, col=zColors, cex=1)
Also, using ggplot2, you can use color and size together, as in:
which might make it a little clearer.
Notes:
The expression
rev(rainbow(100))
reverses the rainbow color scale, so that red goes with the larger values ofdens
.Unfortunately, you cannot combine a continuous legend (color) and a discrete legend (size), so you would normally get two legends. The expression
guide="none"
hides the size legend.Here's the plot:
Here are some solutions using the
ggplot2
package.I attach the plots as well: