Search code examples
rstatisticstime-series

Time Series Plot


The following R codes produce one graph for time series, while the next chunks of codes produce 8 graphs.

births <- scan("http://robjhyndman.com/tsdldata/data/nybirths.dat")

birthstimeseries <- ts(births, frequency=12, start=c(1946,1))
birthstimeseries

plot.ts(birthstimeseries)

The 2nd chunks of codes:

library(Matrix)

i <- c(1, 3, 8, 4, 2, 7, 6, 9, 1, 4, 10, 5, 11, 2, 12)
j <- c(2, 5, 3, 8, 6, 2, 4, 2, 4, 5, 2, 7, 3, 2, 1)
x <- rpois(15, 5)
M4 <- sparseMatrix(i, j, x = x)
M4_regular_matrix <- as(M4, "matrix")

timeseries <- ts(M4_regular_matrix)
print(timeseries)

plot.ts(timeseries)

The first graph considers ts object to be a single time series, while the 2nd chunks of codes consider 8 different time series. I want to convert the 2nd dataset as a single time series and produce only one graph. How can I do that?


Solution

  • Convert the matrix to a vector, and specify the frequency plus start date:

    timeseries <- ts(as.vector(M4_regular_matrix), frequency = 12, start = c(2023, 1))
    
    plot.ts(timeseries)
    

    enter image description here