【问题标题】:Historical Variance Error Decomposition plot in RR中的历史方差误差分解图
【发布时间】:2020-05-05 11:33:35
【问题描述】:

我在下面的链接中找到了如何估计 R 中 VAR 模型的历史方差分解

Historical Variance Error Decompotision Daniel Ryback

Daniel Ryback 在 excel 图中显示结果,但我想用 ggplot 准备它,所以我创建了一些线来获得它,但是,我在 ggplot 中得到的图与 Daniel 在 Excel 中显示的图非常不同。我在 excel 中复制并得到与 Daniel 相同的结果,所以我准备 ggplot 的方式似乎存在错误。有没有人建议得出 excel 结果?

见下面我的代码

library(vars)
library(ggplot2)
library(reshape2)

此代码是在运行上面链接中 Daniel Ryback 开发的代码定义 HD 功能后运行的

data(Canada)
ab<-VAR(Canada, p = 2, type = "both")
HD <- VARhd(Estimation=ab)
HD[,,1] 

ex <- HD[,,1]
ex1 <- as.data.frame(ex) # transforming the HD matrix as data frame #
ex2 <- ex1[3:84,1:4] # taking our the first 2 rows as they are N/As #
colnames(ex2) <- c("Emplyment", "Productivity", "Real Wages", "Unemplyment") # renaming columns #
ex2$Period <- 1:nrow(ex2) # creating an id column #
col_id <- grep("Period", names(ex2)) # setting the new variable as id #
ex3 <- ex2[, c(col_id, (1:ncol(ex2))[-col_id])] # moving id variable to the first column #
molten.ex <- melt(ex3, id = "Period") # melting the data frame #

ggplot(molten.ex, aes(x = Period, y = value, fill = variable)) + 
geom_bar(stat = "identity") + 
guides(fill = guide_legend(reverse = TRUE))

ggplot 版本

Excel 版本

【问题讨论】:

  • 您知道如何在 BQ SVAR 模型而不是 VAR 上运行 Daniel Ryback 的函数吗?

标签: r ggplot2


【解决方案1】:

不同之处在于ggplot2variable 因子进行排序,并以与excel 不同的顺序绘制它。如果在绘制之前重新排序因子,它将把“失业”放在底部,将“就业”放在顶部,就像在 excel 中一样:

molten.ex$variable <- factor(molten.ex$variable, levels = c("Unemployment",
                                                "Real Wages",
                                                "Productivity",
                                                "Employment"))

ggplot(molten.ex, aes(x = Period, y = value, fill = variable)) + 
  geom_bar(stat = "identity", width = 0.6) + 
  guides(fill = guide_legend(reverse = TRUE)) +
  # Making the R plot look more like excel for comparison... 
  scale_y_continuous(limits = c(-6,8), breaks = seq(-6,8, by = 2)) +
  scale_fill_manual(name = NULL, 
                    values = c(Unemployment = "#FFc000",  # yellow
                               `Real Wages` = "#A4A4A4",  # grey
                               Productivity = "#EC7C30",  # orange
                               Employment = "#5E99CE")) + # blue
  theme(rect = element_blank(),
        panel.grid.major.y = element_line(colour = "#DADADA"),
        legend.position  = "bottom",
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        legend.key.size = unit(3, "mm"))

给予:

大致匹配 Daniel Ryback 帖子中的 excel 图:

【讨论】:

  • 这对于更改情节中的条形非常有效,但是,传说似乎保持不正确的顺序。例如,蓝色条应该是失业,橙色条应该是实际工资。你知道是否也有办法纠正那个项目吗?
  • 在调用的values = 部分中,它定义了分配给每个组的颜色。我已经根据链接帖子中的 excel 图分配了它。从数据来看,这似乎是正确的——70 年的失业率为负数,而就业率为正数。我想你可能在 excel 中混合了变量?
  • Andrew 我感谢您的帮助,我已经更好地理解了代码,并且效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 2020-12-25
  • 2012-05-12
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
相关资源
最近更新 更多