[R] Save generic plot to file (before rendering to device)

David Winsemius dwinsemius at comcast.net
Mon Jul 11 20:15:19 CEST 2011

On Jul 11, 2011, at 12:08 PM, jeroen00ms wrote:

> I am looking for a way to save a plot (graphics contents) to a file  
> after the
> plot has been calculated but before it has been rendered. More  
> specifically,
> assume that I made a plot that took a very long time to produce, I  
> would
> like to save this plot to a generic file that I can later, on a  
> different
> machine, render to either PDF, PNG, SVG using the usual R graphics  
> devices,
> without recalculating the graphical contents.
> As a toy example, suppose this is my plot function:
> testplot <- function(){
>  Sys.sleep(10); #very long and complicated procedure
>  plot(cars);
> }

 > ?Devices
 > ?capabilities
 > capabilities()
     jpeg      png     tiff    tcltk      X11     aqua http/ftp  sockets
     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE
   libxml     fifo   cledit    iconv      NLS  profmem    cairo
     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE     TRUE

I have all of the requested capabilities (and more.)

> So the use case is that after running testplot() which took  
> potentially 30
> days to calculate,

Unfortunately you basically threw away all of the intermediate steps  
by plot()-ting at the very end, since that function returns NULL. If  
you had plotted first and then executed return(data_object) and then  
did no operations, you would be able to capture the last calculation  

data_object <- .Last.value

Plotting with lattice or ggplot may leave a plot object in the  
workspace. If done within a function you will need to return it so it  
doesn't disappear.

> I would like to send a file to my colleagues that they
> can load in R and send to their png or pdf or svg devices just as if  
> they
> would have made the plot themselves, without having to re-run the  
> code.

You can also save a data (or function) object to an .Rdata file with  
save(objname, file="filename.Rdata")  and your colleagues could then  
load("filename.Rdata") in R.

> --
> View this message in context: http://r.789695.n4.nabble.com/Save-generic-plot-to-file-before-rendering-to-device-tp3659999p3659999.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT

More information about the R-help mailing list