Search code examples
rggplot2gridextrar-grid

How to get hold of the base graphics plot.new to combine with others via arrangeGrob?


I have the following simplified use-case. Basically I have some ggplot2 plots that I'd like to combine with another that is generated using the basic graphics library plot.new() etc:

p1 <- generate_ggplot1(...)
p2 <- generate_ggplot2(...)
p3 <- generate_ggplot3(...)

# how to get hold of the plot output and make it available as 
# p4 for arrangeGrob?
plot.new()
...

final <- gridExtra::arrangeGrob(p1, p2, p3, p4, layout_matrix = rbind(c(1,2), c(3,4)), widths=c(7,7), heights=c(7,7))
ggplot2::ggsave(filename=output.file,plot=final,width=14,height=14)

What options are there to do that? separate from rewriting p4 to be native ggplot2


Solution

  • try this,

    library(gridGraphics)
    library(grid)
    library(gridExtra)
    library(ggplot2)
    
    grab_grob <- function(...){
      grid.echo(...)
      grid.grab()
    }
    
    b <- grab_grob(function() plot(cars))
    g <- ggplot()
    
    grid.arrange(b, g)