I have a dataframe with an X and Y column and a third column with an additional variable (let's call it "ABC"). I would like to create a heatmap that visualizes how ABC depends on the X and Y variables but using bins instead of the raw X and Y data.

I tried to use the kernel density estimation function (kde2d) but it only seems to be able to estimate the density of the X and Y variables, such as image.plot(kde2d(dat$X,dat$Y,n=50)).

I have managed to manually create the same bin matrix as used by the kde2d function, store it as an additional variable, and get the mean value of ABC for each bin:

halfbinX = (diff(range(dat$X))/(bins-1))/2
halfbinY = (diff(range(dat$Y))/(bins-1))/2
catX = cut(dat$X, seq(min(dat$X)-halfbinX, max(dat$X) + halfbinX,length.out=bins+1), labels=F)
catY = cut(dat$RelY, seq(min(dat$Y)-halfbinY, max(dat$Y) + halfbinY,length.out=bins+1), labels=F)
dat$cat = factor(paste(catX,catY,sep="."))
ABCmeans = tapply(dat$ABC, dat$cat, mean)

However, the problem is that those means are not smoothed across the bins such as the kde2d function does for calculating the density for X,Y values.

Is there any function or better way to do what I'd like to do? Any help is appreciated.


1 Answer 1


It sounds like you're looking for Nadaraya-Watson kernel regression. The np pacakage handles that well.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.