2

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

zx8754
  • 52,746
  • 12
  • 114
  • 209
SkyWalker
  • 13,729
  • 18
  • 91
  • 187
  • I don't know if it is possible with `gridextra`, but check `gridbase`; [Combine base and ggplot graphics in R figure window](https://stackoverflow.com/questions/14124373/combine-base-and-ggplot-graphics-in-r-figure-window/14125565#14125565), [plots generated by 'plot' and 'ggplot' side-by-side](https://stackoverflow.com/questions/13021863/plots-generated-by-plot-and-ggplot-side-by-side) – Henrik Aug 26 '17 at 20:42

1 Answers1

5

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)
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Many thanks for your answer! I understand `gridExtra::arrangeGrob`, is it not possible to still use this API rather than `grid` directly? otherwise and for completeness how can I achieve my full OP use-case taking into account layout and also final output to `ggsave`? – SkyWalker Aug 26 '17 at 21:30
  • I don't really know what you mean. You can use `arrangeGrob` instead of `grid.arrange` to store the composite grob. – baptiste Aug 26 '17 at 22:20
  • That's exactly what I meant – SkyWalker Aug 26 '17 at 23:04
  • Your solution works but as pointed out in the other answer you referred to, the final result for me too is that the captured plot is squeezed by too aggressive margins, somehow its dimension gets screwed when capturing and/or arranging the layout. – SkyWalker Aug 28 '17 at 11:26
  • An idea, is there a way to differently color the background of the graphic plot to see what margins are eating up all the space and then tackle those? – SkyWalker Aug 28 '17 at 11:28