Search code examples
rtransparencycontourfillkernel-density

2D Kernel Density Plot and Transparent Contour Fills in R


I have tried to use ks package in R to plot a two-dimensional kernel density diagram with transparent fills Here is my code.

library(ks)
B<-matrix(c(3.02,2.71,8.05,1.36,1.18,2.64,1.48,5.51,3.25,2.66,0.15,2.25,3.09,2.49,3.37,4.56,0.15,0.57,2.6,0.24,0.27,0.1,0.34,0.24,0.24,0.24,0.23,0.34,0.36,0.1,12,0.88,0.15,0.2,0.1,11.19,0.1,0.1,0.26,22.3),nrow=20,ncol=2)
f<-kde(B)
png(filename = "KDE_test.png",  units="in", width=5, height=5, res=100)
plot(f,display="filled.contour2",xlim=c(-1,5),ylim=c(-3.5,5),lwd=0,lwd.fc=0.1,drawlabels=FALSE,col=c("transparent",rgb(0,0,255, maxColorValue=255, alpha=50),rgb(0,0,255, maxColorValue=255, alpha=100),rgb(0,0,255, maxColorValue=255, alpha=150)))
dev.off()

However, I ended up getting a KDE plot with jagged edges. Sorry, I couldn't upload my picture, but please run this code and you will see the image I am talking about.

Does anyone know how to fix this problem or am I doing something wrong?

Many thanks.

enter image description here


Solution

  • You can use the gridsize option of kde.

    library(ks)
    B <- matrix(c(3.02,2.71,8.05,1.36,1.18,2.64,1.48,5.51,3.25,2.66,0.15,2.25,3.09,
      2.49,3.37,4.56,0.15,0.57,2.6,0.24,0.27,0.1,0.34,0.24,0.24,0.24,0.23,
      0.34,0.36,0.1,12,0.88,0.15,0.2,0.1,11.19,0.1,0.1,0.26,22.3),
      nrow=20, ncol=2)
    
    f<-kde(B, gridsize=1024)
    
    plot(f,display="filled.contour2", xlim=c(-1,5), ylim=c(-3.5,5), 
        lwd=0, lwd.fc=0.1, drawlabels=FALSE, 
        col=c("transparent", 
           rgb(0,0,255, maxColorValue=255, alpha=50), 
           rgb(0,0,255, maxColorValue=255, alpha=100), 
           rgb(0,0,255, maxColorValue=255, alpha=150)))
    

    enter image description here