rlayoutgraphicspar

Combining plots that use `graphics::layout` internally


Here is a reprex:

simple_plot <- function(col = "black") {
  plot(x = 1:10, y = 1:10, col = col)
}

## wrapper function with a "complex" layout
plot_fun <- function() {
  mat <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2, byrow = TRUE)
  lay <- layout(mat = mat)
  simple_plot(col = "red")
  simple_plot(col = "blue")
  simple_plot(col = "green")
  simple_plot(col = "black")
}

par(mfrow = c(2, 1))
simple_plot()
plot_fun()  # simple_plot() would obviously work

Solution

  • You can capture base graphics and convert them to grid grobs using gridGraphics::echoGrob(). This is what the cowplot package uses under the hood.

    In your case, you would simply do:

    a <- gridGraphics::echoGrob(simple_plot)
    b <- gridGraphics::echoGrob(plot_fun)
    
    gridExtra::grid.arrange(a, b)
    

    enter image description here