Rnaldinho Rnaldinho - 11 months ago 67
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
data <- Canada
data <- data.frame(data[,1:2])
var <- VAR(data, p=2, type = "both")

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

# Response
# Lower & Higher

#Create DataFrame and Plot
irf_df <- data.frame(irf$irf,irf$Lower,irf$Upper)
irf_df$T<-seq.int(nrow(irf_df)) #T
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 Source

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")

Output: enter image description here