3
$\begingroup$

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?

$\endgroup$
2
$\begingroup$

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

library("lattice")
library("MASS")

set.seed(1);
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)),
                       z=as.vector(dens$z))
         panel.levelplot(tmp$x, tmp$y, tmp$z, contour=TRUE,
                         subscripts=1:nrow(tmp), region=FALSE, ...)
         panel.xyplot(x, y, ...)
       })

lattice plot

$\endgroup$
1
  • $\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$ – user3720596 Dec 22 '15 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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