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

Jim Lemon jim at bitwrit.com.au
Sat Mar 26 04:20:19 CET 2011


On 03/26/2011 07:19 AM, Pam Allen wrote:
> 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
> colours instead of points, i.e.:
>
> plot(dat$date, dat$flow, col=colour, type="l") ##Doesn't work, because the
> line is continuous
>
Hi Pam,
I couldn't get the above example to run, and I've arrived at this 
problem rather late. However, if I have guessed your original question 
correctly, this might help:

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)
plot(data$date,data$flow,type="n")
library(plotrix)
color.scale.lines(data$date,data$flow,
  col=color.scale(data$flow,extremes=c("blue","red")))

The "clplot" function in plotrix is similar and might also be of interest.

Jim



More information about the R-help mailing list