2013-07-22 42 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)