[R] drawing a line that shifts from solid to broken

Jim Lemon jim at bitwrit.com.au
Sun Jan 31 10:42:55 CET 2010


On 01/31/2010 02:33 AM, Jamie Smith wrote:
> I am graphing longitudinal data from three time points. I'd like to draw a
> solid line from point 1 to point 2, and then a dashed line from point 2 to
> point 3. It works if I do it in two steps:
>
>> first.vector<- c(mean(year1$variable1), mean(year2$variable1))
>> second.vector<- c(NA, mean(year2$variable1), mean(year3$variable1))
>> plot(first.vector, type="b", xlim=c(1,3))
>> lines(second.vector, type="b", lty=2)
>
> It's clunky, though, and I have a bunch of these to do. Can I streamline it?

Hi Jamie,
Time to start writing functions...

multi.line.plot<-function(x,y,type="b",lty=par("lty"),
  col=par("fg"),...) {

  if(missing(y) && !missing(x)) {
   y<-x
   x<-1:length(y)
  }
  nlines<-length(y)-1
  if(length(lty) < nlines) lty<-rep(lty,length.out=nlines)
  if(length(col) < nlines) col<-rep(col,length.out=nlines)
  plot(x,y,type="n",...)
  for(i in 1:nlines) lines(x[i:(i+1)],y[i:(i+1)],type=type,
   lty=lty[i],col=col[i])
}

This lets you draw lines with different line types and colors. Now you 
could do things with line widths if you really wanted to.

Jim



More information about the R-help mailing list