4

From https://stackoverflow.com/a/13295880 I learned how to arrange two plots with aligned plot areas.

My question is: How can I get an object of the arranged plots?

Example:

require(ggplot2)
require(gridExtra)

A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +coord_flip() 
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 

gA <- ggplot_gtable(ggplot_build(A))
gB <- ggplot_gtable(ggplot_build(B))
maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
gA$widths[2:3] <- as.list(maxWidth)
gB$widths[2:3] <- as.list(maxWidth)

## works:
grid.arrange(gA, gB, ncol=1)

## does not work:
theplot <- grid.arrange(gA, gB, ncol=1, plot=FALSE)
Community
  • 1
  • 1
Andreas
  • 1,106
  • 9
  • 26
  • there's no `plot` argument for `grid.arrange` – baptiste Apr 11 '13 at 06:52
  • 1
    @baptiste There is in the help page of grid.arrange: `Value: return a frame grob; side-effect (plotting) if plot=T` – Andreas Apr 11 '13 at 07:03
  • good catch, the help page hasn't been updated since the early version where this was dropped. – baptiste Apr 11 '13 at 07:16
  • 5
    i've updated the help page (on github), and `grid.arrange` now also returns the grob invisibly. – baptiste Apr 11 '13 at 07:24
  • Very nice! That will be handy. Much appreciated. Unfortunately I do not have enough reputation to upvote a comment, sorry :-( – Andreas Apr 11 '13 at 07:30
  • With this question, I have now gained enough reputation, so upvoted now. Thanks again. – Andreas Apr 11 '13 at 08:49
  • thanks, but I don't think upvoting comments matters much (as I understand, this feature is only present to prevent never-ending streams of "Me too!".) – baptiste Apr 11 '13 at 08:55

1 Answers1

5

Use function arrangeGrob() to save both plots as object.

theplot <- arrangeGrob(gA, gB, ncol=1)
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • does not work for me: `Error in arrangeGrob(gA, gB, ncol = 1, plot = FALSE) : input must be grobs!` – Andreas Apr 11 '13 at 07:01