Inverse of ggplotGrob?

前端 未结 3 1165
遇见更好的自我
遇见更好的自我 2020-12-02 14:35

I have a function which manipulates a ggplot object, by converting it to a grob and then modifying the layers. I would like the function to return a ggplot object not a grob

相关标签:
3条回答
  • 2020-12-02 14:38

    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.

    0 讨论(0)
  • 2020-12-02 14:39

    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.

    0 讨论(0)
  • 2020-12-02 14:41

    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

    0 讨论(0)
提交回复
热议问题