KatyB - 11 months ago 65

R Question

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?

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.

```
library(ggplot2)
# 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") +
theme_bw()
```

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.