Search code examples
rplottime-seriesadvanced-custom-fields

How to calculate ACF for multiple series and plot them all at once?


I need to do an AR test and plot acf for many series. I can do it one by one like,

library(dplyr)
library(feasts)
library(tsibble)
data1 <- rnorm(70, 5, 2)
data2 <- rnorm(70, 3, 1)
data3 <- rnorm(70, 8, 3)
MONTH <- seq(as.Date("2010-01-01"), by = "day", length.out = 70)
tstable <- data.frame(MONTH, data1,data2,data3)
tstable%>%as_tsibble(index = MONTH)%>%ACF(data1,lag_max = 7)%>%autoplot()
tstable%>%as_tsibble(index = MONTH)%>%ACF(data2,lag_max = 7)%>%autoplot()
tstable%>%as_tsibble(index = MONTH)%>%ACF(data3,lag_max = 7)%>%autoplot()

This is too much repetitive work. Is there a way to do the acf test and plot the series all at once? It doesn't matter if they are on the same graph or not. But it would be nice if different series can be labeled. Thanks.


Solution

  • How about this:

    plotACF <- function(data, vars, time_index, lag_max=7, rows=NULL){
      if(is.null(rows))rows <- ceiling(sqrt(length(vars)))
      glist <- list()
      for(i in 1:length(vars)){
        glist[[i]] <- data%>%
          as_tsibble(index = .data[[time_index]])%>%
          ACF(.data[[vars[i]]],lag_max = lag_max)%>%
          autoplot() + ggtitle(vars[i])
      }
      glist[["nrow"]] = rows
      do.call(cowplot::plot_grid, glist)
    }
    
    plotACF(tstable, c("data1", "data2", "data3"), "MONTH")
    

    enter image description here