Search code examples
rplot

Save a plot in an object


In ggplot2, one can easily save a graphic into a R object.

p = ggplot(...) + geom_point()      # does not display the graph
p                                   # displays the graph

The standard function plot produces the graphic as a void function and returns NULL.

p = plot(1:10)     # displays the graph
p                  # NULL

Is it possible to save a graphic created by plot in an object?


Solution

  • base graphics draw directly on a device.

    You could use

    1- recordPlot

    2- the recently introduced gridGraphics package, to convert base graphics to their grid equivalent

    Here's a minimal example,

    plot(1:10) 
    
    p <- recordPlot()
    plot.new() ## clean up device
    p # redraw
    
    ## grab the scene as a grid object
    library(gridGraphics)
    library(grid)
    grid.echo()
    a <- grid.grab()
    
    ## draw it, changes optional
    grid.newpage()
    a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))
    grid.draw(a)