简体   繁体   中英

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.

在此处输入图像描述

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)))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM