Search code examples
rscatter-plotkernel-densitydensity-plot

Kernel density scatter plot in R


I saw a beautiful plot and I'd like to recreate it. Here's an example showing what I've got so far:

# kernel density scatterplot
library(RColorBrewer)
library(MASS)
greyscale <- rev(brewer.pal(4, "Greys"))
x <- rnorm(20000, mean=5, sd=4.5); x <- x[x>0]
y <- x + rnorm(length(x), mean=.2, sd=.4)
z <- kde2d(x, y, n=100)
plot(x, y, pch=".", col="hotpink")
contour(z, drawlabels=FALSE, nlevels=4, col=greyscale, add=T)
abline(c(0,1), lty=1, lwd=2)
abline(lm(y~x), lty=2, lwd=2)

I'm struggling to fill the contours with colour. Is this a job for smoothScatter or another package? I suspect it might be down to my use of kde2d and, if so, can someone please explain this function or link me to a good tutorial?

Many thanks!

P.S. the final image should be greyscale


Solution

  • Seems like you want a filled contour rather than jus a contour. Perhaps

    library(RColorBrewer)
    library(MASS)
    greyscale <-brewer.pal(5, "Greys")
    x <- rnorm(20000, mean=5, sd=4.5); x <- x[x>0]
    y <- x + rnorm(length(x), mean=.2, sd=.4)
    z <- kde2d(x, y, n=100)
    
    filled.contour(z, nlevels=4, col=greyscale, plot.axes = {
        axis(1); axis(2)
        #points(x, y, pch=".", col="hotpink")   
        abline(c(0,1), lty=1, lwd=2)
        abline(lm(y~x), lty=2, lwd=2)
    })
    

    which gives

    enter image description here