Rnaldinho Rnaldinho - 1 month ago 20
R Question

Add confidence band to R IRF Plot

I use following example code to plot an impulse response function:

# Load data and apply VAR
library("vars")
data(Canada)
data <- Canada
data <- data.frame(data[,1:2])
names(data)
var <- VAR(data, p=2, type = "both")

# Apply IRf
irf <- irf(var, impulse = "e", response = "prod", boot = T, cumulative = FALSE, n.ahead = 20)
str(irf)
plot(irf)

# Response
irf$irf
# Lower & Higher
irf$Lower
irf$Upper

#Create DataFrame and Plot
irf_df <- data.frame(irf$irf,irf$Lower,irf$Upper)
irf_df$T<-seq.int(nrow(irf_df)) #T
irf_df
plot(data.frame(irf_df$T, irf_df[1]), type="l", main="Impulse Response")
abline(h=0, col="blue", lty=2)


It looks like it works so far, though I sense that the code could be improved.

Would it be possible to add a confidence band for the Lower and Upper bounds of the confidence interval?

Answer

If you want to plot the Lower and Upper bands, you can use the lines() function, setting the y-limits of the plot if desired.

plot(irf_df$T, irf_df$prod, type="l", main="Impulse Response",
    ylim = c(min(irf_df$prod.1), max(irf_df$prod.2)) * 1.1)
abline(h=0, col="blue", lty=2)
lines(irf_df$T, irf_df$prod.1, lty = 2)
lines(irf_df$T, irf_df$prod.2, lty = 2)

For a fancier plot with the confidence band filled in, use polygon. Here, we set up an empty plot, then plot the polygon, and finally overlay the line. Also note here that there's no need to set up a new data.frame: we can simply use values from the irf() output:

plot(irf$irf$e, type = "n", main = "Impulse Response",
    ylim = c(min(irf$Lower$e), max(irf$Upper$e)))
polygon(x = c(seq_along(irf$irf$e), rev(seq_along(irf$irf$e))),
        y = c(irf$Lower$e, rev(irf$Upper$e)),
        lty = 0, col = "#fff7ec")
lines(irf$irf$e)

Output: enter image description here