0

I have a function that returns an arrangeGrob. I would like the access the individual ggplot objects to make them an input to say ggplotly. I tried looking at the structure of the arrangeGrob object, but there doesn't seem that there is a way to get that. I don't need to plot the plot I need to use it elsewhere. In the example below, I'd like to be able to get back each of the (ggplot) p1 in the list given to arrangeGrob.

library(ggplot2)
library(gridExtra)
p1 = ggplot(data = pressure, aes(x = temperature, y = pressure)) + geom_line() + theme_light()

p = arrangeGrob(grobs = list(p1, p1), ncol=2, widths=c(1,1))
str(p)
grid.draw(p)
grid.draw(p$grobs[[1]])
grid.draw(p$grobs[[2]])

str(p1)
str(p$grobs[[2]])
plot(p$grobs[[2]])

library(plotly)
ggplotly(p$grobs[[2]])
Courvoisier
  • 904
  • 12
  • 26
  • `p2` seems to be missing – hrbrmstr Oct 11 '18 at 13:14
  • 1
    regardless of ^^ try doing `p$grobs[[1]] ; ggplot_gtable(ggplot_build(p1))` and compare the output. The plots have been rendered and there's [no going back](https://stackoverflow.com/questions/26499608/inverse-of-ggplotgrob) – hrbrmstr Oct 11 '18 at 13:17
  • @hrbrmstr p2 = p1 now `p$grobs[[1]] ; ggplot_gtable(ggplot_build(p1))` are indeed the same. So there is no way to get the ggplto object back? that's dissapointing – Courvoisier Oct 11 '18 at 13:25
  • Aye, but not unexpected due to the fact that since it is rendered all context is gone (no data, no factors, groups, etc). – hrbrmstr Oct 11 '18 at 13:28
  • @hrbrmstr what is the reason anyone would want to return a grob instead of a ggplot object? – Courvoisier Oct 11 '18 at 13:41
  • 1
    To use it in other `grid` graphics context (ggplot2 isn't the only package that uses `grid`) or even as an object in a ggplot2 plot itself (you can annotate a plot with an arbitrary grob) – hrbrmstr Oct 11 '18 at 13:43
  • And it's lighter, isn't it? That's the only price I would pay for information loss. – Courvoisier Oct 11 '18 at 14:01
  • 1
    oh yes. pre-gtable objects come with all the data frames too. can be pretty large – hrbrmstr Oct 11 '18 at 14:10

1 Answers1

0

not sure why you'd want to do this but you can easily fool arrangeGrob's simple class check and delay the conversion to a grob to drawing time,

library(ggplot2)
library(gridExtra)
library(grid)

p1 = ggplot()

pl <- lapply(list(p1, p1), function(p) {class(p) <- c('dummy','grob'); p})

drawDetails.dummy <- function(x, recording = FALSE) {
  class(x) <- c('ggplot')
  grid.draw(ggplotGrob(x))
}

g = arrangeGrob(grobs = pl, widths=c(1,2))
grid.newpage()
grid.draw(g)

pp1 <- g$grobs[[1]]
class(pp1) <- class(p1)
identical(p1,pp1)
  • because i want to edit it. Also see my question. I explicitly say I want to use the objects as inputs to ggplotly. – Courvoisier Oct 15 '18 at 10:44