[R] Plot, lines and disordered x and y

Ben Bolker bolker at ufl.edu
Fri Jan 23 20:19:05 CET 2009


Todor Kondic <dolichenus <at> gmail.com> writes:

> 
> Ok, here is a bit more information:
> 
> R is version 2.7.1 (2008-06-23)
> 

> 
> So what we should see here is a flat y=0 for x<0 and identity for x>0.
> Instead, we have a saw-like shape where e.g y(x=-1) is connected to
> y(x=1) .
> 
> This is of course minor  (actually asymptotically, no annoyance at
> all). I am just mentioning it for 'completness' sake and because a
> divinely ideal plotting function should cope with data given in any
> order.
> 

  The problem here is that a divinely ideal plotting function
for other people would allow data to be in any order, and plot
it respecting that order, rather than automatically assuming
it should be sorted.  The less intrusive alternative, allowing
a "sorted" flag to plot, is an example of "feature creep" --
once we succumb to the temptation to add this, there are a million
other special cases that people want, and plot ends up with
a million options (and 2^(10^6) interactions among the options
that lead to surprising outcomes).  While it seems like a pain,
it really makes more sense in the long run to require users
to rearrange their data.  Here's a straightforward way:


x <- c(1,-1,2,-2,3,-3,4,-4,5,-5)
y <- c(1,0,2,0,3,0,4,0,5,0)
plot(x,y,type='l')   #bad
plot(x,y) # this is how it should look like

d <- data.frame(x,y)
d <- d[order(d$x),]
plot(d,type="b")

  This works because plot() knows how to handle
a list with elements named "x" and "y", and a data
frame is such a list.

  If you want you can write your own function so you
never have to think about this again:

mydivinelyidealplot <- function(x,y,...) {
   d <- data.frame(x,y)
   d <- d[order(d$x),]
   plot(d,...)
}

(you might want to give it a slightly shorter name
like "myplot", though. It is technically possible
to call it "plot" (and mask the real plot function),
but it would be a Really Really Really Bad Idea to do so)

  cheers
    Ben Bolker




More information about the R-help mailing list