Search code examples
rggplot2data-visualizationfacet

Using ggplot's facet_wrap with autocorrelation plot


I want to create a ggplot figure of autocorrelations for different subgroups of my data.

Using the forecast package, I manage to produce a ggplot figure for the whole sample like this:

library(tidyverse)
library(forecast)

df <- data.frame(val = runif(100),
                key = c(rep('a', 50), key = rep('b', 50)))

ggAcf(df$val) 

Which produces:

enter image description here

But now I'm trying the following to produce the facets and it doesn't work:

ggplot(df) +
  ggAcf(aes(val)) +
  facet_wrap(~key) 

Any ideas?


Solution

  • A possible solution building out the acf values and plot manually.

    library(tidyverse)
    library(forecast)
    
    df <- data.frame(val = runif(100),
                     key = c(rep('a', 50), key = rep('b', 50)))
    
    df_acf <- df %>% 
      group_by(key) %>% 
      summarise(list_acf=list(acf(val, plot=FALSE))) %>%
      mutate(acf_vals=purrr::map(list_acf, ~as.numeric(.x$acf))) %>% 
      select(-list_acf) %>% 
      unnest() %>% 
      group_by(key) %>% 
      mutate(lag=row_number() - 1)
    
    df_ci <- df %>% 
      group_by(key) %>% 
      summarise(ci = qnorm((1 + 0.95)/2)/sqrt(n()))
    
    ggplot(df_acf, aes(x=lag, y=acf_vals)) +
      geom_bar(stat="identity", width=.05) +
      geom_hline(yintercept = 0) +
      geom_hline(data = df_ci, aes(yintercept = -ci), color="blue", linetype="dotted") +
      geom_hline(data = df_ci, aes(yintercept = ci), color="blue", linetype="dotted") +
      labs(x="Lag", y="ACF") +
      facet_wrap(~key)
    

    acf with calc ci