KatyB KatyB - 9 months ago 57
R Question

Altering the acf plot produced by R

This may or may not be a very simplistic question. But I am trying to alter the acf plot produced in R and am having no luck. I would like to change the way that the acf looks i.e. change from the basic plot. The figure displays the normal acf produced by R on the left and the acf I would like on the right, is there a way of changing this? enter image description here

I have tried typing 'changing acf plot in R' into various search engines but cannot find a suitable solution. So far I have stored the acf output:

a <- acf(blah)
xyplot(acf~lag,data=a,type = "l")

This returns a lineplot of the acf, but does not retain the 95% confidence interval. Does anyone have any suggestions?

Answer Source

I can get something similar to the plot you want by using ggplot2. I've used the ldeaths table for an example here. The crucial point is probably extracting the values from the acf object into a data.frame. From there you can pretty much plot whatever you want with it.


# compute acf without plotting
acz <- acf(ldeaths, plot=F)

# 95% confidence interval limits
ci <- qnorm((1 + 0.95)/2)/sqrt(sum(!is.na(series)))  

# convert to data frame
acd <- data.frame(lag=acz$lag, acf=acz$acf)

# use data frame for ggplot
ggplot(acd, aes(lag, acf)) + geom_area(fill="grey") +
    geom_hline(yintercept=c(ci, -ci), linetype="dashed") +

enter image description here

You can familiarise yourself with ggplot2 by looking over the documentation here. This will help you customize the plot further.

The confidence interval is not exported by the acf function - this calculation is done inside the plot.acf function. So when drawing the ACF with ggplot, you need to compute the CI bounds yourself.