[R] lines with colored segments

Jim Lemon jim at bitwrit.com.au
Mon Nov 5 09:57:03 CET 2012


On 11/05/2012 12:29 AM, David Stevens wrote:
> Hello all
>
> I'm trying to create a plot similar to a plot.default(..., type='b')
> with points plotted connected by lines that leave small gaps between the
> end of the line and the point symbol, BUT, with each line segment's
> color controlled by a category. plot... draws the line color uniformly
> according to the first color in a color sequence, ignoring the
> remainder.  I can use segments() to give the proper colors using the x,y
> data, but those segments don't have the small gaps around the symbols.
> Somewhere, somehow, plot... either only draws the shortened segments, or
> draws the full segment, blanks out the space around the the symbol then
> adds the symbol (or, maybe something more sophisticated). Obviously I'm
> not the first to want to do this. Has anyone addressed this?
>
Hi David,
Try this:

library(plotrix)
x<-c(0,cumsum(rnorm(99)))
y<-c(0,cumsum(rnorm(99)))
xydist<-sqrt(x*x+y*y)
plot(x,y,main="Random walk plot",xlab="X",ylab="Y",type="n")
color.scale.lines(x,y,col=2+(diff(xydist)>0))
boxed.labels(x,y,labels=1:100,border=FALSE,cex=0.5)

This colors a random walk with green if the "step" advances away from 
the start and red if it regresses toward the start. Just pass your 
colors in the "col=" argument.

Jim




More information about the R-help mailing list