Search code examples
rggplot2lattice

Combine a ggplot2 object with a lattice object in one plot


I would like to combine a ggplot2 with a lattice plot object. Since both packages are based on grid I was wondering whether this is possible? Ideally, I would do everything in ggplot2 but I cannot plot a 3d scatter.

So assume I have the following data:

set.seed(1)
mdat <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100),
                   cluster = factor(sample(5, 100, TRUE)))

First, I want to create a scatterplot matrix in ggplot2:

library(ggplot2)
library(gtools)
library(plyr)

cols <- c("x", "y", "z")
allS <- adply(combinations(3, 2, cols), 1, function(r)
    data.frame(cluster = mdat$cluster,
          var.x = r[1],
          x = mdat[[r[1]]],
          var.y = r[2],
          y = mdat[[r[2]]]))

sc <- ggplot(allS, aes(x = x, y = y, color = cluster)) + geom_point() +
      facet_grid(var.x ~ var.y)

So far so good. Now I want to create a lattice 3d scatterplot with all the variables together:

library(lattice)
sc3d <- cloud(z ~ x + y, data = mdat, groups = cluster)

Now I would like to combine sc and sc3d in one single plot. How can I achieve that? Maybe with the help of grid or gridExtra (pushViewport, arrangeGrob?)? Or can I produce a 3d scatterplot in ggplot? Ideally, I would like to see the 3d plot in the empty panel pf the ggplot but I guess that's asked even too much, so for starters I would be very happy to learn how we could arrange these two plots side by side.

ggplot lattice


Solution

  • library(gridExtra); library(lattice); library(ggplot2)
    grid.arrange(xyplot(1~1), qplot(1,1))
    

    enter image description here

    You can replace the empty panel by the lattice grob within the gtable, but it doesn't look very good due to the axes etc.

    g <- ggplotGrob(sc)
    lg <- gridExtra:::latticeGrob(sc3d)
    ids <- which(g$layout$name == "panel")
    remove <- ids[2]
    g$grobs[[remove]] <- lg
    grid.newpage()
    grid.draw(g)
    

    enter image description here