Reputation: 51
How to plot ACF plot and PACF plot for a time series in R using ggplot2?
Upvotes: 4
Views: 15121
Reputation: 6168
Besides the forecast::ggAcf
function, it also quite fast to do it yourself with ggplot. The only nuisance is that acf
does not return the bounds of the confidence interval, so you have to calculate them yourself.
# plot acf with ggplot
ggacf <- function(series) {
significance_level <- qnorm((1 + 0.95)/2)/sqrt(sum(!is.na(series)))
a<-acf(series, plot=F)
a.2<-with(a, data.frame(lag, acf))
g<- ggplot(a.2[-1,], aes(x=lag,y=acf)) +
geom_bar(stat = "identity", position = "identity") + xlab('Lag') + ylab('ACF') +
geom_hline(yintercept=c(significance_level,-significance_level), lty=3);
# fix scale for integer lags
if (all(a.2$lag%%1 == 0)) {
g<- g + scale_x_discrete(limits = seq(1, max(a.2$lag)));
}
return(g);
}
#example: plot correlogram of an AR(1) process
require('stats');
ggacf(arima.sim(model=list(ar=0.9), n=300));
Below you can see the output from the snippet. The plot
Upvotes: 6
Reputation: 1363
There's plenty of ways to do this and you can find them if you spend a few minutes googling it or searching this site.
One way is ggAcf
and ggPacf
from the forecast
package. They create ggplot2
objects which you can then customize using ggplot syntax and parameters.
series <- rnorm(300)
plot <- ggAcf(series)
Upvotes: 16