【问题标题】:Changing aesthetics in ggplot generated by svars package in R改变 R 中 svars 包生成的 ggplot 中的美学
【发布时间】:2021-01-19 22:26:11
【问题描述】:

我正在使用svars 包生成一些 IRF 图。这些图是使用ggplot2 渲染的,但是我需要一些帮助来改变一些美学。

有什么方法可以更改阴影置信带的填充和 alpha 以及实线的颜色?我知道在ggplot2 中,您可以将fillalpha 参数传递给geom_ribbon(以及colgeom_line),只是不确定如何在此包源的plot 函数中执行相同操作代码。

# Load Dataset and packages
library(tidyverse)
library(svars)
data(USA)

# Create SVAR Model
var.model <- vars::VAR(USA, lag.max = 10, ic = "AIC" )
svar.model <- id.chol(var.model)

# Wild Bootstrap

cores <- parallel::detectCores() - 1
boot.svar <- wild.boot(svar.model, n.ahead = 30, nboot = 500, nc = cores)

# Plot the IRFs

plot(boot.svar)

我还在查看历史分解图的命令(见下文)。有什么办法可以省略前两个方面,只在同一方面绘制底部三行?

hist.decomp <- hd(svar.model, series = 1)
plot(hist.decomp)

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    在调用plot 后重置aes_params 可以轻松实现您想要的第一个结果。为了你的第二个目标。可能有一种方法可以操纵ggplot 对象。相反,我下面的方法从头开始构建情节。基本上,我从vars:::plot.hd 复制并粘贴了数据整理代码,并为所需系列过滤了准备好的数据集:

    # Plot the IRFs
    
    p <- plot(boot.svar)
    
    p$layers[[1]]$aes_params$fill <- "pink"
    p$layers[[1]]$aes_params$alpha <- .5
    p$layers[[2]]$aes_params$colour <- "green"
    p
    

    # Helper to convert to long dataframe. Source: svars:::plot.hd
    hd2PlotData <- function(x) {
      PlotData <- as.data.frame(x$hidec)
      if (inherits(x$hidec, "ts")) {
        tsStructure = attr(x$hidec, which = "tsp")
        PlotData$Index <- seq(from = tsStructure[1], to = tsStructure[2], 
                              by = 1/tsStructure[3])
        PlotData$Index <- as.Date(yearmon(PlotData$Index))
      }
      else {
        PlotData$Index <- 1:nrow(PlotData)
        PlotData$V1 <- NULL
      }
      dat <- reshape2::melt(PlotData, id = "Index")
      dat
    }
    
    hist.decomp <- hd(svar.model, series = 1)
    
    dat <- hd2PlotData(hist.decomp)
    
    dat %>% 
      filter(grepl("^Cum", variable)) %>% 
      ggplot(aes(x = Index, y = value, color = variable)) + 
      geom_line() + 
      xlab("Time") + 
      theme_bw()
    

    编辑 更改构面标签的一种方法是通过自定义labeller 函数。有关通过数据更改构面标签的不同方法,请参阅here

    myvec <- LETTERS[1:9]
    
    mylabel <- function(labels, multi_line = TRUE) {
      data.frame(variable = labels) 
    }
    p + facet_wrap(~variable, labeller = my_labeller(my_labels))
    

    【讨论】:

    • 感谢@stefan,这个解决方案对我有用!还有一个问题,有没有办法在我的第一个图中传递标签向量来重新标记构面标题?
    • 你好坦加。我刚刚使用一种方法进行了编辑以实现此目的以及指向第二种方法的链接。
    • 完美解决方案@stefan,非常感谢您的帮助!!
    猜你喜欢
    • 1970-01-01
    • 2012-06-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2019-05-09
    相关资源
    最近更新 更多