2017-06-22 36 views
1

我想为我的数据的不同子组创建一个ggplot的自相关图。使用ggplot的facet_wrap与自相关图

使用forecast包,我设法产生整个样本这样一个ggplot图:

library(tidyverse) 
library(forecast) 

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

ggAcf(df$val) 

主要生产:

enter image description here

但现在我想以下生产方面,它不起作用:

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

任何想法?

+0

请检查类关键变量,并确保它是一个因子变量。 –

+0

is.factor(df $ key) [1] TRUE –

回答

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) 

acf with calc ci

+0

正是我在找的东西。编辑:哦,但错误带是硬编码... –

+1

答案已经更新,以'ggAcf'相同的方式计算置信区间 –

1
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)) 

enter image description here

或者:

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)) 

enter image description here

+0

作品也谢谢!我的真实世界数据集有更高的组数,有时候会有不同的组数,所以我必须在这种情况下修改代码。 –