I have a data frame containing a time column and 3 time series on the other columns, created with the ts() function. Here’s an example:
data.frame(time = 1:10, ts1 = rnorm(10), ts2 = rnorm(10,2,50), ts3 = rpois(10, 20)) %>% mutate(across(2:4, ts))
I’d like to make 3 separate line plots with the time column on the x axis and the time series on the y axis, however pivot_longer()doesn’t seem to work on TSobjects, giving the error:
Error in `pivot_longer()`:
! Can't convert `ts3` <ts> to <double>.
Which means facet_wrap() isn’t an option, as far as I understand.
I need to have the columns as time series objects for further analysis, is there a way to make these plots in a single function or do I have to create 3 separate plots?
Clarification: I need 3 separate plots, not the 3 time series in the same plot, since they vary a lot in scale.
>Solution :
Using matplot.
> matplot(df[-1], type='l', xlab='time', ylab='value')
> legend('bottomleft', lty=1:3, col=1:3, legend=names(df[-1]), bty='n', horiz=TRUE)
To get it on three panels
> par(mfrow=c(1, 3))
> for (i in 2:4) plot(df[, i], main=names(df)[i], ylab='value')
Data:
> dput(df)
structure(list(time = 1:10, ts1 = structure(c(1.37095844714667,
-0.564698171396089, 0.363128411337339, 0.63286260496104, 0.404268323140999,
-0.106124516091484, 1.51152199743894, -0.0946590384130976, 2.01842371387704,
-0.062714099052421), tsp = c(1, 10, 1), class = "ts"), ts2 = structure(c(67.2434827111743,
116.332269635055, -67.443035055617, -11.9394383408686, -4.6660668196829,
33.7975199035037, -12.2126460708036, -130.822771045239, -120.023346428776,
68.0056672865096), tsp = c(1, 10, 1), class = "ts"), ts3 = structure(c(18L,
12L, 27L, 21L, 21L, 18L, 23L, 22L, 15L, 22L), tsp = c(1, 10,
1), class = "ts")), class = "data.frame", row.names = c(NA, -10L
))

