首页 > 解决方案 > 有没有办法在单个情节下绘制 2 个或更多 acfs

问题描述

我有一个时间序列数据框。我有两个连续变量,我需要为其绘制自相关 (acf) 函数。我试图用来plot_grid()确保两个图显示在一个窗口中,但这没有发生。这是示例:

#df is dataframe; col1 and col2 are continuous variables

p1 <- acf(df$col1,lag.max = 5 ,plot = TRUE) 
p2 <- acf(df$col2,lag.max = 5 ,plot = TRUE)
plot_grid(p1, p2, nrow = 2,ncol =1,rel_heights = c(2/1,2/1),rel_widths = c(2/2,2/2))
    f <- structure(list(Date = structure(c(1505779200, 1505779500, 1505779800, 
 1505780100), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
     A = c(212.429693925327, 211.464088210329, 211.653306685973, 
     210.981936189015), B= c(75.9448191760481, 76.2501222022257, 
     76.1316674891558, 76.8299563088116)), row.names = c(NA, 4L
 ), class = "data.frame")
p1 <- acf(f$A, lag.max = 5, plot = FALSE) 
p2 <- acf(f$B, lag.max = 5, plot = FALSE)

cowplot::plot_grid(autoplot(p1), autoplot(p2), nrow = 2)

标签: r

解决方案


plot_grid来自cowplot包(我认为)并适用于基于网格的图形对象(即来自ggplot2/的输出lattice)。acf()使用基本图形。使用的东西par(mfrow ...)应该可以工作,如下所示:

orig_pars <- par(mfrow=c(1,2))
acf(df$col1,lag.max = 5 ,plot = TRUE) 
acf(df$col2,lag.max = 5 ,plot = TRUE)
pars(orig_pars) ## reset

或者你可以

  • 环顾四周寻找基于网格的 ACF 绘图解决方案:有人可能已经写过ggacf或等效的
  • acf()对象中提取数据并使用 lattice/ggplot 创建自己的图

推荐阅读