Search code examples
rplottime-series

Plotting Time series with different colors in R


I want to plot a time series with different colors based on factors. I tried splitting the time series by factor, then plotting using

plot(x1, col= "orange", xlab="Time", font.main=2, cex.main=1.5,
   ylim = c(-8, 10.5), ylab = "Y", main= "X")


lines(x2, col= "red")
  lines(x3, col="yellow")

But this is the result:

Plot

It's almost near to what i need, but of course i want to remove those lines which connect the different parts. Thank you in advance


Solution

  • You could do this:

    a <- rnorm(200)
    k <- sample(c("red", "green", "blue", "brown"), 200, replace = T)
    plot(a, type = "h", col = k)
    

    enter image description here