[R] Help with plotting a line that is multicoloured based on levels of a factor

Pamela Allen pallen at hatfieldgroup.com
Thu Mar 17 23:33:41 CET 2011


 

 

Hi All, 

 

I'm trying to plot data that is a time series of flows that are associated
with a specific level, and I would like each level to represent a colour
in a line plot.  Here is some data that approximates what I'm using:

 

date=c(1:300)

flow=sin(2*pi/53*c(1:300))

levels=c(rep(c("high","med","low"),100))

data=cbind.data.frame(date, flow, levels)

 

the "levels" column represents the levels of flow.  What I've done so far
is to plot this data using coloured points corresponding with each flow
level:

 

colour=ifelse(data$levels=="high","red",

                ifelse(data$levels=="med","green",

                ifelse(data$levels=="low","blue","")))

plot(date, flow, col=colour)

 

What I would like to do instead is to plot the line of this data, not the
points.  i.e., 

plot(date, flow, type="l")

 

But I would like the colour of the line to change with each level, i.e.,

plot(date, flow, type="l", col=colour)

 

But this doesn't work because the line is continuous and the colours are
discrete.  I looked into using clipplot, but I'm not sure how I would
specify limits that would give different sections of the line correct
colours.  Does anyone know of a way to draw a line with different colours?
One way I thought of was to plot each level of flow separately and then
build the plot up, i.e., 

plot(data$date[data$levels=="high"], data$flow[data$levels=="high"],
col="red", type="l")

lines(data$date[data$levels=="med"], data$flow[data$levels=="med"],
col="green", type="l")

lines(data$date[data$levels=="low"], data$flow[data$levels=="low"],
col="blue", type="l")

 

But the line fills in data gaps, so this doesn't work.

 

Any help would be much appreciated!  Thank you.

 

-Pam Allen

pallen at hatfieldgroup.com

 

 



More information about the R-help mailing list