[R] if/else for plot/lines?

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 7 12:26:58 CET 2007

On Fri, 7 Dec 2007, Roger Levy wrote:

> I'm interested in writing a function that constructs a new plot on the
> current graphics device if no plot exists there yet, but adds lines to
> the existing plot if a plot is already there.  How can I do this?  It
> seems to me that the exists() function might be co-opted to do this, but
> it's not obvious how.

exists() will not help with graphics devices, whose state is not stored in 
R objects that exists() can test for.

Note that it is rare for a graphics device to be open and not contain a 
plot.  But in those circumstances par("usr") will be c(0,1,0,1) which 
would be unusual after a plot.

A simple way to test if a non-null device is active is dev.cur() > 1.

However, I doubt if you want to add lines to any old plot that happens to 
be on the device, and there is no general way to tell if the existing 
plot is suitable (it need not be the last plot made, for example).
So I can only see this goal as achievable within a constrained set of 

(A further complication is that a graphics device can display either base 
or grid graphics, and you can't add base graphics to a grid plot or v.v.)

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

More information about the R-help mailing list