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

Jeroen Ooms jeroen.ooms at stat.ucla.edu
Mon Aug 1 12:47:05 CEST 2011


Bumping this one up because the 'before.plot.new' solution turned out
to be sub-optimal after all.

>> It should be possible to do this with a before.plot.new hook, right?
>
> Yes, sure, if you treat the first and last plot separately.

It turns out that the before.plot.new hook does not is not triggered
at the right moments. I'm not sure if this is intended behavior or
incorrect implementation. What I was expecting is a hook/event that is
triggered every time before a new graphics frame is opened. E.g. if
there is an open PDF device and some plots are printed, the number of
times the hook is called should be exactly equal to the number of
pages in the resulting PDF document. Sometimes this works as expected,
sometimes it doesn't.

At the end of this message some example code. In the first example,
the hook works as expected is called 4 times, as there are 4 plots. In
all the other examples the event is either triggered too often or not
triggered at all. I guess the hook is called when the plot.new()
function is explicitly called, which might not always happen.

My question would be if (1) this is the intended behavior for
'before.plot.new', and (2) if yes, would it be possible to define an
additional event that always triggers, and only triggers, if a
completely new graphics device is opened. I.e. whenever a pdf device
would start a new page.

Thank you.


#set the hook (event listener)
setHook("before.plot.new", NULL);
setHook("before.plot.new", function(){ message("Yay! A new plot!")});

#works as expected:
plot(lm(speed~dist, cars), ask=F);

#triggered way too often, once for every partition of the plot
plot(mtcars);

#not triggered at all by lattice
library(lattice);
dotplot(speed~dist, cars);

#not triggered at all by ggplot2
library(ggplot2);
qplot(speed, dist, data=cars);



More information about the R-help mailing list