Search code examples
rggplot2gridviewvisualizationgrob

Combining two grobs , one of them created using grid.draw


I am trying to combine two graphical objects (grob) to a single plot - one of them created with "standard ggplot()" call, the other using grid.draw() on a ggplot_gtable object (based on this thread).

library(ggplot2)
library(grid)
library(gridExtra)

plot_gtable <- function(x) {
  grid::grid.draw(ggplot_gtable(ggplot_build(x)))
}

plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
plot2 <- plot_gtable(ggplot(mtcars, aes(mpg)) + geom_dotplot())

grid.arrange(plot1, plot2)

Error in gList(structure(list(wrapvp = structure(list(x = structure(0.5, class = "unit", valid.unit = 0L, unit = "npc"), : only 'grobs' allowed in "gList"

Created on 2018-12-12 by the reprex package (v0.2.1)

Apparently, calling grid.draw results in NULL object, not a grob, which seems to be the reason why grid.arrange() fails in this case.

I tried with and without calling grid::grid.newpage first.

I tried using grid::viewport and gridExtra::arrangeGrob and ggpubr::ggarrange and cowplot::plot_grid and also patchwork package, all to no avail.

How can I create a combined plot with those objects?


Solution

  • When combining plots and/or grobs using grid.arrange you want to use the actual object rather than trying to plot it. This is why plot2 is NULL as it is drawn rather than returned, and so can't be combined. So don't draw it before combining the plots.

    library(ggplot2)
    library(gridExtra)
    
    # example ggplot
    plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
    # example gtable
    plot2 <- ggplotGrob(plot1)
    
    grid.arrange(plot1, plot2)