Plot() 脉冲响应函数 - 显示多于一比一window?

Plot() impulse response function - show more than one in one window?

我估计了一个 VAR - 模型,我想在一个 window 中显示多个 IRF。 plot() 有可能吗?我试过 par(mfrow) 但没有用。有什么提示或想法吗?

提前致谢

irf1 <- irf(Var1, n.ahead = 10, ortho = T,response="y2")
plot(irf1,main = "",xlab ="years",ylab="growth rate")

如果 ggplot2 是适合您的解决方案,此功能可以提供帮助:

例子

library(tidyverse)

tsp.var.irf <- function(irf){
  
  if (class(irf) %in% "varirf") {
  } else{
    stop("Only 'varirf' class object from vars::irf()")
  }
  
  
  fortify <- function(data){
    result <- vector(mode = "list",length = 0L)
    for (d in 1:length(data)) {
      result[[length(result)+1]]<- tibble::tibble(imp = names(data)[d],
                                                  lag = 0:{nrow(data[[d]])-1},
                                                  tibble::as_tibble(data[[d]]))
    }
    data <- tidyr::unnest(tibble::tibble(result),cols = result)
    return(data)}
  
  data_irf <- fortify(irf$irf)
  data_lower <- fortify(irf$Lower)
  data_upper <- fortify(irf$Upper)
  suppressMessages(
    plot_data <- tibble::add_column(data_irf,type = "mean") %>%
      dplyr::full_join(tibble::add_column(data_lower,type = "lower")) %>%
      dplyr::full_join(tibble::add_column(data_upper,type = "upper")) %>%
      tidyr::pivot_longer(cols = -c(imp,lag,type)) %>%
      dplyr::mutate(imp = paste(imp,"(imp.)"),
                    name = paste(name,"(res.)")))
  
  plot <- ggplot2::ggplot(plot_data) +
    ggplot2::geom_line(ggplot2::aes(x = lag,value,
                                    lty = type),show.legend = F) +
    ggplot2::facet_grid(cols = ggplot2::vars(imp),
                        rows = ggplot2::vars(name)) +
    ggplot2::scale_linetype_manual(values = c("lower"=2,
                                              "upper"=2,
                                              "mean"=1)) +
    ggplot2::geom_hline(yintercept = 0,lty = 3) +
    ggplot2::scale_x_continuous(labels = as.integer)
  return(plot)
}

library(vars)
#> Loading required package: MASS
#> 
#> Attaching package: 'MASS'
#> The following object is masked from 'package:dplyr':
#> 
#>     select
#> Loading required package: strucchange
#> Loading required package: zoo
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#> 
#> Attaching package: 'strucchange'
#> The following object is masked from 'package:stringr':
#> 
#>     boundary
#> Loading required package: urca
#> Loading required package: lmtest
data("Canada")
model <- VAR(Canada,3)
model_irf <- irf(model)
tsp.var.irf(model_irf)

reprex package (v1.0.0)

创建于 2022-02-11