19

acf我们可以在ACF plot基础R图中制作。

x <- lh
acf(x)

在此处输入图像描述

以下代码可用于获取ACF plotin ggplot2

conf.level <- 0.95
ciline <- qnorm((1 - conf.level)/2)/sqrt(length(x))
bacf <- acf(x, plot = FALSE)
bacfdf <- with(bacf, data.frame(lag, acf))

library(ggplot2)
q <- ggplot(data=bacfdf, mapping=aes(x=lag, y=acf)) +
       geom_bar(stat = "identity", position = "identity")
q

在此处输入图像描述

问题

如何获得线条而不是条形或如何设置条形的宽度以使它们看起来像线条?谢谢

4

5 回答 5

24

你可能最好通过线段绘制geom_segment()

library(ggplot2)

set.seed(123)
x <- arima.sim(n = 200, model = list(ar = 0.6))

bacf <- acf(x, plot = FALSE)
bacfdf <- with(bacf, data.frame(lag, acf))

q <- ggplot(data = bacfdf, mapping = aes(x = lag, y = acf)) +
       geom_hline(aes(yintercept = 0)) +
       geom_segment(mapping = aes(xend = lag, yend = 0))
q

在此处输入图像描述

于 2013-07-22T13:50:38.040 回答
5

使用宽度 = 0 的 geom_errorbar 怎么样?

ggplot(data=bacfdf, aes(x=lag, y=acf)) + 
    geom_errorbar(aes(x=lag, ymax=acf, ymin=0), width=0)
于 2013-07-22T13:49:34.067 回答
4

@康拉德;试试下面的代码:

library(ggfortify)
p1 <- autoplot(acf(AirPassengers, plot = FALSE), conf.int.fill = '#0000FF', conf.int.value = 0.8, conf.int.type = 'ma') 
print(p1) 
library(cowplot) 
ggdraw(switch_axis_position(p1, axis = 'xy', keep = 'xy'))

在此处输入图像描述

于 2016-01-18T15:54:01.487 回答
2

预测包中提供了一个函数ggtsdisplay,它用ggplot. x是模型拟合的残差 ( fit$residuals)。

forecast::ggtsdisplay(x,lag.max=30)
于 2017-08-31T16:24:19.273 回答
1

根据您的回答,我合成了一个 ggplot ACF / PACF 绘图方法:

    require(zoo)
    require(tseries)
    require(ggplot2)
    require(cowplot)

    ts= zoo(data[[2]]) # data[[2]] because my time series data was the second column

    # Plot ACP / ACF with IC
    # How to compute IC for ACF and PACF :
    # https://stats.stackexchange.com/questions/211628/how-is-the-confidence-interval-calculated-for-the-acf-function
    ic_alpha= function(alpha, acf_res){
      return(qnorm((1 + (1 - alpha))/2)/sqrt(acf_res$n.used))
    }

    ggplot_acf_pacf= function(res_, lag, label, alpha= 0.05){
      df_= with(res_, data.frame(lag, acf))
      
      # IC alpha
      lim1= ic_alpha(alpha, res_)
      lim0= -lim1
      
      
      ggplot(data = df_, mapping = aes(x = lag, y = acf)) +
        geom_hline(aes(yintercept = 0)) +
        geom_segment(mapping = aes(xend = lag, yend = 0)) +
        labs(y= label) +
        geom_hline(aes(yintercept = lim1), linetype = 2, color = 'blue') +
        geom_hline(aes(yintercept = lim0), linetype = 2, color = 'blue')
    }

    acf_ts= ggplot_acf_pacf(res_= acf(ts, plot= F)
                   , 20
                   , label= "ACF")
    pacf_ts= ggplot_acf_pacf(res_= pacf(ts, plot= F)
                         , 20
                         , label= "PACF")
    # Concat our plots
    acf_pacf= plot_grid(acf_ts, pacf_ts, ncol = 2, nrow = 1)
    acf_pacf

结果:

在此处输入图像描述

于 2021-04-11T10:13:35.947 回答