Inverse of ggplotGrob?

Solution 1:

I would say no. ggplotGrob is a one-way street. grob objects are drawing primitives defined by grid. You can create arbitrary grobs from scratch. There's no general way to turn a random collection of grobs back into a function that would generate them (it's not invertible because it's not 1:1). Once you go grob, you never go back.

You could wrap a ggplot object in a custom class and overload the plot/print commands to do some custom grob manipulation, but that's probably even more hack-ish.

Solution 2:

You can try the following:

p = ggplotify::as.ggplot(g)

For more info, see https://cran.r-project.org/web/packages/ggplotify/vignettes/ggplotify.html

It involves a little bit of a cheat annotation_custom(as.grob(plot),...), so it may not work for all circumstances: https://github.com/GuangchuangYu/ggplotify/blob/master/R/as-ggplot.R

Solution 3:

Have a look at the ggpubr package: it has a function as_ggplot(). If your grob is not too complex it might be a solution!

I would also advise to have a look at the patchwork package which combine nicely ggplots... it is likely to not be what you are looking for but... have a look.