Skip to content

if/else for plot/lines?

5 messages · Roger Levy, Henrique Dallazuanna, Brian Ripley +2 more

#
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.

Many thanks,

Roger
#
Try this:

if(length(dev.list()) == 0) plot(rnorm(100), type="l") else (lines(rnorm(100)))
On 07/12/2007, Roger Levy <rlevy at ucsd.edu> wrote:

  
    
#
On Fri, 7 Dec 2007, Roger Levy wrote:

            
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 
circumstances.

(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.)
#
On Dec 7, 2007 4:28 AM, Roger Levy <rlevy at ucsd.edu> wrote:
You might want to look at the ggplot2 package,
http://had.co.nz/ggplot2/, which exposes plots as objects that can be
easily manipulated.

Hadley
#
The simplest way would be to have a flag, an indicator variable that 
stores a value that indicates if a plot has been done before.  Something 
like this

plot (do my first plot here...)
is.plot=T

.... later in the code...

if (is.plot) {plot (do new plot here)} else {lines(add lines to the 
previous plot)}


Julian
Roger Levy wrote: