1

I used the ggarrange() function in R to create a combined plot with two plots generated from ggplot2 like follows:

library(ggpubr)
plotfn <- function(){
  disp_hist_ggplot1 <- ggplot(mtcars, aes(disp)) + geom_histogram()
  disp_hist_ggplot2 <- ggplot(mtcars, aes(disp)) + geom_histogram()

  disp_hist_combine <-  ggarrange(disp_hist_ggplot1, disp_hist_ggplot2, ncol=2, nrow=1)
  return (disp_hist_combine)}
  p <- plotfn()
  p

Now, the "disp_hist_combine" contains a plot class as "[1] "gg" "ggplot" "ggarrange"", but I want to dissemble it and get the two individual ggplot object again from the disp_hist_combine. How can I get it? Is there any functions that can recover the ggplot from the ggarrange ?

I just wrap the code into a function. Now I just want to find a unit test method to test the function plotfn(). Testthat doesn't work any more on the class of ("gg" "ggplot" "ggarrange"").

JamesD
  • 56
  • 1
  • 4
  • 1
    Is there some reason you can't just use disp_hist_ggplot1 and disp_hist_ggplot2 directly? – jrlewi Jan 09 '18 at 02:06
  • I don't think so. `ggpubr::ggarrange` is a wrapper around `cowplot::plot_grid`, which handles the plots by converting them to the `gtable` format. Since other grid objects / base plots can also be converted to gtable, not all gtable objects can be converted back into a ggplot. A similar question has been asked before regarding ggplotGrob [here](https://stackoverflow.com/questions/26499608/inverse-of-ggplotgrob). The common consensus was that the ggplot->grob conversion is a one-way street. – Z.Lin Jan 09 '18 at 02:09
  • @lewisjr2, I made a function and the return of this function is a ggarrange object. Now I want to use testthat to test this function but it does not work on the ggarrange. the test that only works on ggplot. [link](https://rstudio-pubs-static.s3.amazonaws.com/211910_2562df49b8a04c0aaac12fb3da0df7a5.html). As a result, I just want to get the ggplot object back and use the testthat to test it. – JamesD Jan 09 '18 at 02:57
  • @Z.Lin, thank you very much. Maybe I have to think of another way to solve this problem. – JamesD Jan 09 '18 at 02:59
  • 2
    Author of `cowplot::plot_grid()` here. Yes, conversion from ggplot to gtable is a one-way street. There's no way to go back. However, if you want to test specific aspects of the plots you made, that may be possible on the resulting gtable objects. Could you edit your question to explain what exactly it is you want to test? – Claus Wilke Jan 10 '18 at 04:55
  • @ClausWilke, I have updated the code. I just want to test the function which returns a ggarrange object. Could you help me? Thank you! – JamesD Jan 11 '18 at 03:06
  • Not sure what exactly it is you want to test, but I would probably use the `expect_doppelganger()` function from the `vdiffr` package: https://cran.r-project.org/web/packages/vdiffr/README.html – Claus Wilke Jan 11 '18 at 04:21

0 Answers0