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

Jeroen Ooms jeroen.ooms at stat.ucla.edu
Sun Jul 17 12:17:23 CEST 2011


Thanks I didn't know about that. I ended up with something like this.
Is there a more elegant way to do it?

myplots <<- list();
hasplots <<- FALSE;
setHook("before.plot.new", function(...) {
    if(hasplots == FALSE){
      hasplots <<- TRUE;
    } else {
      myplots[[length(myplots)+1]] <<- recordPlot();
    }
});
myfn <- function(mylm){
  plot(mylm, ask=F)
}
mylm <- lm(dist~speed, data=cars);
pdf(tempfile())
dev.control(displaylist="enable")
myfn(mylm);
if(hasplots){
  myplots[[length(myplots)+1]] <- recordPlot();
}
dev.off()





On Sat, Jul 16, 2011 at 8:17 PM, Hadley Wickham <hadley at rice.edu> wrote:
>
> >> Thank you, this is very helpful. One final question regarding this method:
> >> suppose a function prints multiple plots, i.e. multiple pages to a PDF. Is
> >> it possible to record all of these plots at once? The code below only
> >> records the final plot. I would like to record all of them, without
> >> modifying myfn:
> >
> > You cannot, since this takes a snapshot from the current device. You will
> > have to recordPlot() after each plot, actually.
>
> It should be possible to do this with a before.plot.new hook, right?
>
> Hadley
>
> --
> Assistant Professor / Dobelman Family Junior Chair
> Department of Statistics / Rice University
> http://had.co.nz/



More information about the R-help mailing list