在 ACF 图中省略 0 滞后阶数

机器算法验证 r 时间序列 数据可视化 自相关
2022-04-04 21:30:53

如何在 acf 图中省略零滞后顺序?看这张图片:

在此处输入图像描述 由产生

dummy<-c(14,0.004,0.2,1,0.002,-3,-0.042,1.2,-1,1.3,2.1,4,3001,-2,0.3,2,3)
acf(dummy)

高峰值(逻辑上为 1)正在破坏绘图,因为缩放比例太大。我想省略滞后阶数 1 的高峰,以便缩放可以减少到 -0.2 到 0.2,例如,我该怎么做?

4个回答

使用包中的Acf功能forecast

另一种可能的解决方案如下:

# Create an "acf" object called z
z <- acf(dummy)
# Check class of the object
class(z)
# View attributes of the "acf" object
attributes(z)
# Use "acf" attribute to view the first 13 elements (1 = lag at 0)
z$acf[1:13]
# Get rid of the first element (i.e. lag 0)
z$acf[2:13]
# Plot the autocorrelation function without lag 0
plot(x$acf[2:13], 
     type="h", 
     main="Autocorrelation Function", 
     xlab="Lag",     
     ylab="ACF", 
     ylim=c(-0.2,0.2), # this sets the y scale to -0.2 to 0.2
     las=1,
     xaxt="n")
abline(h=0)
# Add labels to the x-axis
x <- c(1:12)
y <- c(1:12)
axis(1, at=x, labels=y)

到目前为止,这回答了最初的问题。运行代码后,您应该会看到如下图所示的图。

在此处输入图像描述

关于向自相关函数添加显着性带,在这种情况下,首先需要在 y 轴上选择更大的尺度。否则,重要波段将超出范围,我们将无法看到它们。

例如:

# Plot the autocorrelation function without lag 0
plot(z$acf[2:13], 
     type="h", 
     main="Autocorrelation Function", 
     xlab="Lag",     
     ylab="ACF", 
     ylim=c(-1,1), # this sets the y scale to -1 to 1
     las=1,
     xaxt="n")
abline(h=0)
# Add labels to the x-axis
x <- c(1:12)
y <- c(1:12)
axis(1, at=x, labels=y)
# Add 5% critical levels
abline(h=c(2/sqrt(17),-2/sqrt(17)),lty=c(2,2))

由于您可能更喜欢巴特利特的近似值而不是那些 5% 的临界值,因此您可以执行以下操作:

# Store length of dummy
n <- length(dummy)
# Create a vector to store Bartlett's standard errors
bart.error <- c() 
# Use a loop to calculate Bartlett's standard errors
for (k in 1:n) {
     ends <- k-1
     bart.error[k] <- ((1 + sum((2*z$acf[0:(ends)]^2)))^0.5)*(n^-0.5)
}
# Create upper bound of interval (two standard errors above zero)
upper.bart <- 2*bart.error[1:12]
# Create lower bound of interval (two standard errors below zero)
lower.bart <- 2*-bart.error[1:12]
# Add intervals based on Bartlett's approximations to ACF plot
lines(upper.bart, lty=2, col="red"); lines(lower.bart, lty=2, col="red")

运行代码后,您应该会看到类似下图的内容。黑色虚线是 5% 的临界值,红色虚线是基于 Bartlett 标准误差的区间。

在此处输入图像描述

我希望这能回答你所有的问题。

使用此代码:

suppose;

x = rnorm(100) ## A typical white noise process

plot(acf(x,plot=F)[1:20])

设置xlimylim例如:

acf(x,20,xlim(1,20),ylim(-0.2,0.5))