carl_pch carl_pch - 9 months ago 43
R Question

Plotting `irf()` plot side by side in R

I am hoping to create side-by-side plots of Impulse Response Function simulations:

library(tsDyn)
data(barry)
mod_var <- lineVar(barry, lag = 2)
irf <- irf(mod_var, impulse = "dolcan",
response = c("dolcan", "cpiUSA", "cpiCAN"), boot = FALSE)
irf1 <- irf(mod_var, impulse = "dolcan", response = "cpiUSA", boot = FALSE)
irf2 <- irf(mod_var, impulse = "cpiCAN", response = "dolcan", boot = FALSE)


Individually,
plot(irf1)
and
plot(irf2)
give me the plot I want, but is there any way to plot them side by side?

I have already tried
par(mfrow=c(1,2))
and the lattice plot solution, but neither seem to work in this particular case.

To provide some additional details: I am hoping to plot them into a single figure in an
R Notebook
environment and will knit the markdown file to a PDF with
pandoc
.

Answer Source

One solution using ggplot2 (and a little bit of dplyr)

library(ggplot2)
library(dplyr)

irf1_df <- data.frame(impulse = "dolcan", response = "cpiUSA", value = irf1$irf$dolcan[ , 1]) %>% mutate(index = 1:n())
irf2_df <- data.frame(impulse = "cpiCAN", response = "dolcan", value = irf2$irf$cpiCAN[ , 1]) %>% mutate(index = 1:n())

irf_df <- rbind(irf1_df, irf2_df)

ggplot(irf_df) +
  geom_hline(yintercept = 0, colour = "red") +
  geom_line(aes(x = index, y = value, colour = impulse)) +
  facet_wrap(~impulse) +
  labs(title = "Orthogonal Impulse Response")

enter image description here