2017-06-22 69 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

作品也謝謝!我的真實世界數據集有更高的組數,有時候會有不同的組數,所以我必須在這種情況下修改代碼。 –