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

Tóth Dénes tdenes at cogpsyphy.hu
Fri Mar 18 01:51:11 CET 2011


Hi!


Not an elegant solution, but seems to work:

date <- c(1:300)
flow <- sin(2*pi/53*c(1:300))
levels <- factor(rep(c("high","med","low"),100))
data <- cbind.data.frame(date, flow, levels)
colours <- as.numeric(levels)+1

# interpolate
resolution <- 0.001
appres <- approx(date,flow,seq(min(date),max(date),resolution))
appres.colour <- rep(colours,each=1/resolution)[1:length(appres[[1]])]

# plot
plot(appres,col=appres.colour,pch=16,cex=0.5)

Of course you should play with the resolution, pch and cex parameters to
get a higher quality plot, or might use other function for interpolation.


Regards,
  Denes




>
>
>
>
> 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
>
>
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list