uli*_*a2_ 4 r data-visualization facet ggplot2
我想为我的数据的不同子组创建自相关的 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)
Run Code Online (Sandbox Code Playgroud)
其产生:
但现在我正在尝试以下方法来生成方面,但它不起作用:
ggplot(df) +
ggAcf(aes(val)) +
facet_wrap(~key)
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
一种可能的解决方案是构建 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)
Run Code Online (Sandbox Code Playgroud)