RPacker RPacker - 1 month ago 12
R Question

R: Plotting IRF manually

Consider following script to plot an impulse response function:

library(vars)
Canada <- Canada * 999
var <- VAR(Canada, p = 2, type = "both")
plot(irf(var, impulse = "rw", response = "U", boot = T, cumulative = FALSE, n.ahead = 20))
plot(irf(var, impulse = "rw", response = "U", boot = T, cumulative = TRUE, n.ahead = 20))


I wonder how I could access the data of the plot (and 95% intervals)?

It would be great to print a plot with a color filled confidence band, a green impulse response line and different axis descriptions. A solution with R's inbuild plot features would be preferred over ggplot.

Thanks!

Answer

You can view the data returned by irf:

library("vars")

# generate some dummy data
df <- data.frame(n=rnorm(100), p=rpois(100, 2))

var <- VAR(df, p = 2, type = "both")
irf <- irf(var, impulse = "n", response = "p", boot = T, 
           cumulative = FALSE, n.ahead = 20)

# inspect coefficients object
str(irf)

All the data you need is accessible from here (e.g. check irf$Lower and irf$Upper).

One way to customise the default plot would be to look at the source of the function being called when you run plot(irf):

vars:::plot.varirf 

In this case it's a bit involved but you can copy the body of this function and edit the code to change the colours, draw a filled polygon and edit the labels of the axes to get them exactly the way you want.