nk027 / bvar

Toolkit for the estimation of hierarchical Bayesian vector autoregressions. Implements hierarchical prior selection for conjugate priors in the fashion of Giannone, Lenza & Primiceri (2015). Allows for the computation of impulse responses and forecasts and provides functionality for assessing results.
https://cran.r-project.org/package=BVAR
Other
48 stars 21 forks source link

Plotting interface #59

Closed nk027 closed 4 years ago

nk027 commented 4 years ago

An interesting extension would be to facilitate using other packages for plotting etc -- primarily ggplot2, but maybe also ggdist, tidybayes or even broom.

This is part of the small project grant and an extension (possibly in the form of an additional package) should be implemented in the near future. For now I've played around with plotting IRF with ggplot2, which may be interesting:

gg_df <- function(x) {

  stopifnot(inherits(x, "bvar_irf"))

  # So we know what's what
  dimnames(x[["quants"]])[[2]] <- x[["variables"]]
  dimnames(x[["quants"]])[[4]] <- x[["variables"]]
  dimnames(x[["quants"]])[[3]] <- seq(dim(x[["quants"]])[3])

  out <- as.data.frame.table(x[["quants"]]) # Magic base R
  colnames(out) <- c("quant", "response", "time", "shock", "value")
  out[["time"]] <- as.integer(out[["time"]]) # Can't be a factor for the x axis

  return(out)
}

df <- gg_df(x)
df_ribbons <- tidyr::pivot_wider(df, names_from = quant)

ggplot(df, aes(x = time, y = value)) +
  facet_grid(response ~ shock) +
  geom_line(aes(color = quant))

ggplot(df_ribbons, aes(x = time)) + 
    facet_grid(response ~ shock) + 
    geom_line(aes(y = `50%`)) + 
    geom_line(aes(y = `16%`)) + 
    geom_line(aes(y = `84%`)) + 
    geom_ribbon(aes(ymin = `16%`, ymax = `84%`), alpha = 0.25)
oDNAudio commented 4 years ago

See BVARverse