2013-07-22 44 views
14

使用acf我們可以根據R圖製作ACF plot圖。ggplot2的ACF圖:geom_bar的設置寬度

x <- lh 
acf(x) 

enter image description here

下面的代碼可以用來獲得ggplot2ACF plot

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 

enter image description here

問題

如何獲得線,而不是酒吧或如何設置酒吧寬度,使它們看起來像行?由於

+2

請注意,這裏有一個'ggplot2'包裝器:https://github.com/dewittpe/qwraps。用'devtools :: install_github(「dewittpe/qwraps」)'安裝。 – krlmlr

+0

這是非常有用的帖子。我想知道是否創建類似Stata的* [雙變量時間序列的交叉相關圖](http://www.stata.com/support/faqs/graphics/gph/graphdocs/cross-correlogram-for-bivariate-time-系列/)*可以使用建議的方法實現? – Konrad

+2

@konrad嘗試以下代碼:'庫(ggfortify) P1 < - 自動繪製(ACF(AirPassengers,情節= FALSE),conf.int.fill = '#0000FF',conf.int.value = 0.8,conf.int (type ='ma') print(p1) 庫(cowplot) ggdraw(switch_axis_position(p1,axis ='xy',keep ='xy'))' – MYaseen208

回答

17

你可能會更好過通過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 

enter image description here

+1

這個答案超舊(並且仍然有用)。只是要注意,你忘了加上'geom_hline(AES(y截距= ciline),線型= 3,顏色= 'darkblue')+ geom_hline(AES(y截距= -ciline),線型= 3,顏色= 'darkblue')'模仿線路中的原始鹼情節 – Romain

+0

虛線:線型= 2 – Rottmann

5

如何使用geom_errorbar與寬度= 0?

ggplot(data=bacfdf, aes(x=lag, y=acf)) + 
    geom_errorbar(aes(x=lag, ymax=acf, ymin=0), width=0) 
3

@konrad用直線段繪製;試試下面的代碼:

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')) 

enter image description here

+2

此代碼沒有產生已附圖中,藍色區域是在你提供的代碼矩形 –

0

從預測包裝內附送的功能ggtsdisplay繪出兩個ACF和PACF與ggplotx是模型擬合的殘差(fit$residuals)。

forecast::ggtsdisplay(x,lag.max=30)