Search code examples
rgraphr-forestplot

How to store forest plot in an object to be recalled in R?


Just a little question on how to store and recall forest plot in R. I am creating forest plot using the meta function in R. I may have the need to store the graph and recall in the viewer at a later time. I've tried with this expression:

forest.meta <- forest(meta,  [...])

where [...] are the options, but when I type "forest.meta", I get a "null" error rather than the graph again in the viewer.

Where I am wrong?

Thank you in advance for any help.


Solution

  • You get NULL because that's what the function returns, much as base R's plot does. It's not like ggplot where an actual plot object is returned for you to manipulate.

    However, all is not lost. Since forest plots using grid graphics, we can grab the contents of the plotting window, store them as a collection of graphical objects, and plot them again later:

    library(meta)
    
    data(Olkin1995)
    
    m1 <- metabin(ev.exp, n.exp, ev.cont, n.cont,
                  data = Olkin1995, subset = c(41, 47, 51, 59),
                  sm = "RR", method = "I",
                  studlab = paste(author, year))
    
    forest(m1)
    

    enter image description here

    # Now grab the plot
    my_plot <- grid::grid.grab()
    

    The plot is now stored as my_plot, so suppose we want to use the plotting window for something else meantime

    plot(1:10)
    

    When we're done, we can recall the exact same plot by doing:

    grid::grid.newpage()
    grid::grid.draw(my_plot)
    

    enter image description here