Store output from gridExtra::grid.arrange into an object

后端 未结 2 1316
遥遥无期
遥遥无期 2020-12-20 12:38

I am placing multiple plots into one image using gridExtra::grid.arrange and would like to have the option of saving the combined plot as an object that could b

2条回答
  •  再見小時候
    2020-12-20 13:21

    Funny that this was asked so recently - I was running into this problem as well this week and was able to solve it in a bit of a hacky way, but I couldn't find any other solution I was happier with.

    Problem 1: ggplotGrob is not found

    I had to make sure ggplot2 is loaded. I don't completely understand what's happening (I admit I don't fully understand imports/depends/attaching/etc), but the following fixes that. I'd be open to feedback if this is very dangerous.

    if (!"package:ggplot2" %in% search()) {
      suppressPackageStartupMessages(attachNamespace("ggplot2"))
      on.exit(detach("package:ggplot2"))
    }
    

    Somebody else linked to this blog post and I think that works as well, but from my (non-complete) understanding, this solution is less horrible. I think.

    Problem 2: no layers in plot

    As you discovered too, fixing that problem allows us to use grid.arrange, but that returns NULL and doesn't allow saving to an object. So I also wanted to use arrangeGrob but I also ran into the above error when gridExtra was not already loaded. Applying the fix from problem 1 again doesn't seem to work (maybe the package is getting de-attached too early?). BUT I noticed that calling grid::grid.draw on the result of arrangeGrob prints it fine without error. So I added a custom class to the output of arrangeGrob and added a generic print method that simply calls grid.draw

    f <- function() {
      plot <- gridExtra::arrangeGrob(...)
      class(plot) <- c("ggExtraPlot", class(plot))
      plot
    }
    print.ggExtraPlot <- function(x, ...) {
      grid::grid.draw(x)
    }
    

    Hooray, now I can open a fresh R session with no packages explicitly loaded, and I can successfully call a function that creates a grob and print it later!


    You can see the code in action in my package on GitHub.

提交回复
热议问题