0
votes

I have a time series of monthly data for 10 years:

myts <- ts(rnorm(12*10), frequency = 12, start = 2001)

Now, I'd like to plot the data but with the x-axis restricted to a range/ticks from Jan - Dec (generic year). Thus, the whole time series should be broken in ten lines where each line starts at Jan and ends at Dec. So multiple lines should be overplotted each other which I'd like to use to visually compare different years. Is there a straight forward command to do that in R?

So far I came up with following solution using matplot which might not be the most sophisticated one:

mydf <- as.data.frame(matrix(myts, 12))
matplot(mydf,type="l")

Time series in one generic year

Or even better would be a way to calculate an average value and the corresponding CI/standard deviation for each month and plot then the average from Jan - Dec as a line and the corresponding CI/standard deviation as a band around the line for the average.

1

1 Answers

0
votes

Consider using ggplot2.

library(ggplot2)
library(ggfortify)
d <- fortify(myts)
d$year <- format(d$Index, "%Y")
d$month <- format(d$Index, "%m")

It's useful to start by reshaping the ts object into a long dataframe. Given the dataframe, it's straightforward to create the plots you have in mind:

ggplot(d, aes(x = month, y = Data, group = year, colour = year)) +
  geom_line()

ggplot(d, aes(x = month, y = Data, group = month)) +  
  stat_summary(fun.data = mean_se, fun.args = list(mult = 1.96))

Result: enter image description here

You can also summarise the data yourself, then plot it:

d_sum <- do.call(rbind, (lapply(split(d$Data, d$month), mean_se, mult = 1.96)))
d_sum$month <- rownames(d_sum)
ggplot(d_sum, aes(x = month, y = y, ymin = ymin, ymax = ymax)) +
  geom_errorbar() +
  geom_point() +
  geom_line(aes(x = as.numeric(month)))

Result: enter image description here