gpt4 book ai didi

r - 使用 ggplot 的 facet_wrap 和自相关图

转载 作者:行者123 更新时间:2023-12-03 11:35:25 28 4
gpt4 key购买 nike

我想为我的数据的不同子组创建自相关的 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)

产生:

enter image description here

但现在我正在尝试以下方法来生成方面,但它不起作用:
ggplot(df) +
ggAcf(aes(val)) +
facet_wrap(~key)

有任何想法吗?

最佳答案

构建 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

关于r - 使用 ggplot 的 facet_wrap 和自相关图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44697596/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com