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

Pam Allen allen_pam at hotmail.com
Fri Mar 25 21:19:51 CET 2011

```Hello again,

I wrote an example that better represents my data, since the coloured points
are actually consecutive, but with variable lengths:

date=as.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)

library(zoo)
z <- zoo(data\$flow, data\$date)
zz=cbind.data.frame(date=as.Date(rownames(cbind.data.frame(rollapply(z, 2,
align = "right", FUN="+")))),flow.change=(rollapply(z, 2, align =
"right",FUN="+" )))
names(zz)=c("date","todays.flow","next.day.flow")
zzz=cbind.data.frame(zz[,1], (zz[,3]-zz[,2]))
names(zzz)=c("date","change.flow")
data2=merge(data, zzz)
rate=zoo(data2\$change.flow,data2\$date)
x=cbind.data.frame(date=as.Date(rownames(cbind.data.frame(rollapply(rate, 2,
align="left", FUN="+")))), sign=rollapply(rate, 2, align="left",FUN="+"))
names(x)=c("date","todays.change","next.day.change")
xx=cbind.data.frame(x[,1],(x[,3]*x[,2]))
names(xx)=c("date","sign")
data2=merge(data2, xx)

data3=cbind(data2,pass1=
ifelse(data2\$flow<0, "extreme.low",
ifelse(data2\$flow>=0.9, "extreme.high","NA")))
data4=cbind(data3, pass2=

ifelse(data3\$flow<0.8&data3\$flow>0&data3\$change.flow>=0&data3\$change>=0&data3\$pass1=="NA","medium"
,

ifelse(data3\$flow<0.7&data3\$flow>0&data3\$change.flow<0&data3\$change<0&data3\$pass1=="NA","medium","NA")))
data4\$pass1=paste(data4\$pass1, data4\$pass2)
data4\$pass1=replace(data4\$pass1, data4\$pass1=="NA NA", "low")

dat=cbind(data4[,1:5], class=
ifelse(data4\$pass1=="extreme.high NA","1.Extreme.High",
ifelse(data4\$pass1=="NA medium","2.Medium",
ifelse(data4\$pass1=="low","3.Low",
ifelse(data4\$pass1=="extreme.low NA","4.Extreme.Low",NA)))))

colour=ifelse(dat\$class=="1.Extreme.High","red",
ifelse(dat\$class=="2.Medium","green",
ifelse(dat\$class=="3.Low","blue",
ifelse(dat\$class=="4.Extreme.Low","purple",""))))
plot(dat\$date, dat\$flow, col=colour)

What I would like to do is to plot this using a line with the correct

plot(dat\$date, dat\$flow, col=colour, type="l") ##Doesn't work, because the
line is continuous

Any help would be much appreciated.  Thank you!

-Pam

--
View this message in context: http://r.789695.n4.nabble.com/Help-with-plotting-a-line-that-is-multicoloured-based-on-levels-of-a-factor-tp3385857p3406309.html
Sent from the R help mailing list archive at Nabble.com.

```