12

I want to save, but not print (for now), a bunch of ggplot()s into a grid (via arrangeGrob(), correct?), then print and retrieve them later.

This is a reboot of an existing question. Strangely, that answer does not work, and I have no idea why. I am using the exact same code.

  library(ggplot2)
  p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
  p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
  library(gridExtra)
  y <- arrangeGrob(p1, p2)
  class(y)
  y

Strangely, that does not (as in the above answer) yield the grid of plots, but:

> class(y)
[1] "gtable" "grob"   "gDesc" 
> y
TableGrob (2 x 1) "arrange": 2 grobs
  z     cells    name           grob
1 1 (1-1,1-1) arrange gtable[layout]
2 2 (2-2,1-1) arrange gtable[layout]

What is going on here?

Community
  • 1
  • 1
maxheld
  • 3,963
  • 2
  • 32
  • 51

1 Answers1

12

The gridExtra package has been updated recently thereby changing how arrangeGrob works internally and what kind of object it returns (now a gtable).

You need to call grid.draw:

grid.draw(y)

resulting plot

Edit: do not use plot() as initially suggested; it will add a grey background, and is only meant to be used for debugging gtables.

baptiste
  • 75,767
  • 19
  • 198
  • 294
Roland
  • 127,288
  • 10
  • 191
  • 288
  • an answer to this other question recommends to **use `grid.draw()`**, *not* `plot()`. I am confused. -> http://stackoverflow.com/questions/31463445/how-do-i-get-rid-of-random-background-grid-from-arrangegrob Author of other answer appears to be package author ... – maxheld Jul 16 '15 at 21:12
  • @maxheld actually this answer does not explain how to save the plot with `ggsave` later in your plot, does it? My problem is the saving, don't know how to change my code without download the development version from ggplot2 – drmariod Nov 19 '15 at 15:02
  • It may be worth mentioning that the output from `grid.draw(x)` appears to be NULL in most cases. To get around this and work with ggsave, I have used `ggpubr::as_ggplot(x)`. This converts the gtable/grobArrange() into a class of `ggplot` which can then be worked with as usual. Additional technical note, I believe `as_ggplot()` builds on code from `cowplot`. – al-obrien Nov 08 '18 at 16:45
  • Is the `grid.draw` mentioned here `grid::grid.draw`? There seems to be no `grid.draw` in `gridExtra`. I opted for `gridExtra::grid.arrange` for a similar object. – Kim Nov 18 '18 at 07:51