【问题标题】:Using ggplot's facet_wrap with autocorrelation plot使用 ggplot 的 facet_wrap 和自相关图
【发布时间】:2017-06-22 11:06:48
【问题描述】:

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

有什么想法吗?

【问题讨论】:

  • 请检查关键变量的类别,确保它是因子变量。
  • is.factor(df$key) [1] TRUE

标签: r ggplot2 data-visualization facet


【解决方案1】:

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

【讨论】:

  • 答案已更新,以与 ggAcf 相同的方式计算置信区间
【解决方案2】:
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))

【讨论】:

  • 也可以,谢谢!我的真实世界数据集的组数更多,有时还会发生变化,因此在这种情况下我必须调整代码。
【解决方案3】:

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 那样在地块上方获得带有刻面标题的横幅,因此最终结果不如上面的答案那么完美。我也无法删除右侧图的 y 轴标签,同时保留左侧图的标签。

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多