What would be the equivalent of geom_density2d in lattice? In essence I'm trying to create this graph with lattice:

enter image description here

I don't think contourplot or levelplot is what i want and when trying it, it gives me a blank plot?


1 Answer 1


Use a custom panel function in which the density is estimated (e.g. using MASS::kde2d()):


dat <- data.frame(x=rnorm(100), y=rt(100, 5))

xyplot(y~x, data=dat,
       panel=function(x, y, ...) {
         dens <- kde2d(x=dat$x, y=dat$y, n=50)
         tmp <- data.frame(x=dens$x,
                       y=rep(dens$y, each=length(dens$x)),
         panel.levelplot(tmp$x, tmp$y, tmp$z, contour=TRUE,
                         subscripts=1:nrow(tmp), region=FALSE, ...)
         panel.xyplot(x, y, ...)

lattice plot

  • $\begingroup$ Ah I see, so there is no native way of doing this directly in lattice then! Thank you for your answer, works well, much obliged! $\endgroup$ Commented Dec 22, 2015 at 8:56

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.