Plot 2D-kernel density from a dataframe: set number of grid positions, bandwith and lims

2.5k views Asked by At

enter image description hereI have a dataframe of two columuns, rappresenting, respectively my "x" and "y" coordinates. I want plot them in a 2D-kernel density plot. I have 91 points. Therefore I have used this script:

x<-read.csv("X_Y.csv", sep=",")
d<-as.matrix(x)
Dgeo<-d[,1]
Dgen<-d[,2] 
dens <- kde2d(Dgeo,Dgen, n=?, lims=c(?,?,?,?))
myPal <- colorRampPalette(c("white","blue","gold", "orange", "red"))
plot(Dgeo, Dgen, pch=20,cex=.5)
image(dens, col=transp(myPal(300),.7), add=TRUE) 
abline(lm(Dgen~Dgeo)) 

I don't understand how I can estimate the values that I have indicated as "?".

Do you any idea?

In the picture is shown what I would like to obtain and on the right what actually I obtain using n=91 and lims=c(-.1, 1.5,-.5,4).

1

There are 1 answers

0
Rorschach On

You could simply do

library(MASS)
set.seed(0)
dat <- data.frame(x=rnorm(100), y=rnorm(100, 2))
dens <- kde2d(dat$x, dat$y)
image(dens)
contour(dens, add=T)

enter image description here

Not sure where transp function is for color