Search code examples
rtime-seriesxts

Is it possible to multicolor a timeseries based on a variable?


I'm interested in adding another dimension of information to a timeseries plot by coloring the series based on another variable. Below is my attempt to do this with the xts package:

library(xts)
# create time series
set.seed(100)
tsvalues <- rnorm(100)
dates <- seq(as.Date("2020-01-01"),length=100,by="days")
xts1 <- xts(x=tsvalues, order.by=dates) 
# create the coloring variable and coloring value
colvar <- rnorm(50, 15, 5)
coloring <- colorRampPalette(terrain.colors(40))
colorval <- coloring(40)[colvar]
# plot
plot(xts1, col=colorval)

Here is the result

Note that the entire series is just a single color whereas what is desired is that the color would vary based on the value of colorval that corresponds to each data point. For instance a basic plot (not a timeseries plot) that contains that correct coloring could be done as follows:

plot(tsvalues, pch = 20, col = colorval)

Basic plot with coloring

Using xts is not a necessary requirement so if there is some other package or even Base R itself in which this can be well accomplished, that would definitely work


Solution

  • You may use lines.

    library(xts)
    # create the coloring variable and coloring value
    colvar <- rnorm(33, 15, 5)
    coloring <- colorRampPalette(terrain.colors(33))
    colorval <- coloring(33)[colvar]
    # plot
    plot(xts1, type="n")
    Map(function(x, y) lines(xts1[x], col=colorval[y]), 
        as.data.frame(t(cbind(1:100, 1:100+1, 1:100+2, 1:100+3)[seq(1, 98, 3),])), 
        1:33)
    

    enter image description here


    Data:

    # create time series
    set.seed(100)
    tsvalues <- rnorm(100)
    dates <- seq(as.Date("2020-01-01"), length=100, by="days")
    xts1 <- xts(x=tsvalues, order.by=dates)