3

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?

Dawny33
  • 8,226
  • 12
  • 47
  • 104

1 Answers1

2

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

rcs
  • 710
  • 1
  • 7
  • 16
  • 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! – user3720596 Dec 22 '15 at 08:56