使用 ggplot 的 facet_wrap 和自相关图

Using ggplot's facet_wrap with autocorrelation plot

我想为我的数据的不同子组创建自相关的 ggplot 图。

使用 forecast 包,我设法为整个样本生成一个 ggplot 图,如下所示:

library(tidyverse)
library(forecast)

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

ggAcf(df$val) 

产生:

但现在我正在尝试以下方法来生成切面,但它不起作用:

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

有什么想法吗?

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


a = subset(df, key == "a")
ap = ggAcf(a$val)

b = subset(df, key == "b")
bp = ggAcf(b$val)


library(grid)
grid.newpage()
pushViewport(viewport(layout=grid.layout(1,2)))
print(ap, vp=viewport(layout.pos.row = 1, layout.pos.col = 1))
print(bp, vp=viewport(layout.pos.row = 1, layout.pos.col = 2))

或者:

grid.newpage()
pushViewport(viewport(layout=grid.layout(1,2)))
print(ap, vp=viewport(layout.pos.row = 1, layout.pos.col = 1))
print(bp, vp=viewport(layout.pos.row = 1, layout.pos.col = 2))

建立 acf 值并手动绘制的可能解决方案。

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)

Adam Spannbauer 的回答非常好,输出与 forecast::ggAcf 的非常相似,可能只是虚线与 ggAcf 产生的虚线不同(这很容易如果需要修复)。

一个快速且可能更简单的替代方法是使用 ggfortify::autoplot 和一个列表来表示您的不同构面值,如下例所示:

# Load ggfortify
require(ggfortify)

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

# Create list with ACF objects for different key values
acf.key <- list()
for (i in 1:length(unique(df$key))) {
  acf.key[[i]] <- acf(df$val[df$key==unique(df$key)[[i]]])
}

# Plot using ggfortify::autoplot
autoplot(acf.key, ncol=2)

不幸的是,似乎无法像标准 ggplot 那样在绘图上方获得带有侧面标题的横幅,因此最终结果不如上面的答案那么完美。我也无法在保留 left-hand-side 图的标签的同时删除 right-hand-side 图的 y-axis 标签。