[R] Colour-coding intervals on a line

Jim Lemon jim at bitwrit.com.au
Sun Aug 13 01:16:51 CEST 2006


Sara-Jane Dunn wrote:
> Hi,
>  
> This is a simple version of something that I am trying to do. If I can
> sort the problem basically, I figure I should be able to sort it for the
> program I'm writing (which would take longer to explain).
>  
> I need to know if there is any way of using different colours for
> different intervals of a line on a graph. Eg. If I plot the line y=x for
> x=1:10, and split this line into 106 intervals (i.e. not a 'nice' number
> of intervals) how could I colour different intervals different colours
> without having to use segments and specify coordinates to join?
>  
Hi Sara-Jane,
This is a problem that I have been facing myself. I wanted to display 
color-coded curves that indicated something depending upon the values 
plotted. This might be useful to you, although you will need the 
functions color.scale and rescale from the plotrix package to make it work.

color.scale.lines<-function(x,y,redrange,greenrange,bluerange,
  scale.to="y",...) {

  lenx<-length(x)
  leny<-length(y)
  nseg<-lenx-1
  if(lenx != leny) {
   warning("x and y are different lengths - some values will be ignored")
   if(lenx>leny) nseg<-leny-1
  }
  if(scale.to=="y")
   lcol<-color.scale(y[1:nseg],redrange,greenrange,bluerange)
  else lcol<-color.scale(x[1:nseg],redrange,greenrange,bluerange)
  segments(x[1:nseg],y[1:nseg],x[2:(nseg+1)],y[2:(nseg+1)],col=lcol,...)
}

plot(0,xlim=c(0,pi),ylim=c(0,1),type="n")
x<-seq(0,pi,length=106)
color.scale.lines(x,sin(x)*10,c(0,1),c(1,0),0,lwd=2)

Jim



More information about the R-help mailing list