2

I am using plot_grid to arrange two plots:

library(ggplot2)
library(cowplot)

d = data.frame(x=rnorm(100), y=rnorm(100), g=sample(c('a', 'b'), 100, replace=T))
p1 = ggplot(d) + geom_point(aes(x=x, y=y, colour=g))
p2 = ggplot(d) + geom_point(aes(x=y, y=x, colour=g))
p = plot_grid(p1, p2, nrow=1)

Question: Is there a way to extract the individual ggplot objects after calling plot_grid? For example, I would like to do something like this:

q = extract_ggplot_objects(p)
q1 = q[[1]]
q2 = q[[2]]
q1 = q1 + theme(legend.position='none')
q2 = q2 + ylab('') + theme(axis.text.y=element_blank(), axis.ticks.y=element_blank())
new_p = plot_grid(q1, q2, nrow=1)

I know that for this specific example, it is easiest to just remove the legend from p1 before calling plot_grid. However, the problem I'm trying to solve is much more complicated and it would be helpful if there were a general way of doing this.

Tung
  • 26,371
  • 7
  • 91
  • 115
adn bps
  • 599
  • 4
  • 16
  • why not just use p1 and p2? – GordonShumway May 22 '18 at 16:30
  • The actual problem is much more complicated, but I chose a simple example just to illustrate what I am trying to do. – adn bps May 22 '18 at 17:05
  • 3
    `plot_grid()` converts the ggplot objects into grid graphics objects (grobs). Once that has happened, you can't go back. It might be best to store your plots in a list, manipulate a you see fit, and then hand to `plot_grid()` as the final step. – Claus Wilke May 23 '18 at 16:04
  • Thanks. It is amazingly difficult to edit grobs :( – adn bps May 25 '18 at 20:51

0 Answers0