1

我分别对几个自变量(相同的依赖)运行分位数回归。我只想在单个图中绘制每个变量的几个分位数的斜率估计值。

这是一个玩具数据:

set.seed(1988)

y <- rnorm(50, 5, 3)
x1 <- rnorm(50, 3, 1)
x2 <- rnorm(50, 1, 0.5)

# Running Quantile Regression 
require(quantreg)
fit1 <- summary(rq(y~x1, tau=1:9/10), se="boot")
fit2 <- summary(rq(y~x2, tau=1:9/10), se="boot")

我只想绘制分位数的斜率估计。因此,我放弃parm=2plot

 plot(fit1, parm=2)
 plot(fit2, parm=2)

现在,我想将这两个图合并到一个页面中。

到目前为止我已经尝试过什么;

  1. 我尝试设置par(mfrow=c(2,2))和绘制它们。但它正在产生一个空白页。
  2. 我试过使用gridExtra和 gridGraphics 没有成功。尝试将基础图转换为 Grob 对象,如此处所述
  3. 尝试使用文档中的函数layout函数
  4. 我正在尝试查看plot.rqs. 但我无法理解它是如何绘制置信带的(我只能绘制分位数上的系数)或在mfrow那里更改参数。

谁能指出我哪里出错了?我应该查看源代码plot.rqs并更改那里的任何参数吗?

4

2 回答 2

3

虽然quantreg::plot.summary.rqs有一个mfrow参数,但它使用它来覆盖par('mfrow')以便对parm值进行分面,这不是您想要做的。

一种替代方法是解析对象并手动绘图。您可以从 and 中提取 tau 值和系数矩阵fit1fit2它们只是每个 tau 的值列表,因此在 tidyverse 语法中,

library(tidyverse)

c(fit1, fit2) %>%    # concatenate lists, flattening to one level
    # iterate over list and rbind to data.frame
    map_dfr(~cbind(tau = .x[['tau']],    # from each list element, cbind the tau...
                   coef(.x) %>%    # ...and the coefficient matrix, 
                       data.frame(check.names = TRUE) %>%    # cleaned a little
                       rownames_to_column('term'))) %>% 
    filter(term != '(Intercept)') %>%    # drop intercept rows
    # initialize plot and map variables to aesthetics (positions)
    ggplot(aes(x = tau, y = Value, 
               ymin = Value - Std..Error, 
               ymax = Value + Std..Error)) + 
    geom_ribbon(alpha = 0.5) + 
    geom_line(color = 'blue') + 
    facet_wrap(~term, nrow = 2)    # make a plot for each value of `term`

刻面图

如果您愿意,可以从对象中拉出更多,添加原始的水平线,否则会变得疯狂。


另一种选择是使用magick捕获原始图像(或使用任何设备保存并重新读取它们)并手动组合它们:

library(magick)

plots <- image_graph(height = 300)    # graphics device to capture plots in image stack
plot(fit1, parm = 2)
plot(fit2, parm = 2)
dev.off()

im1 <- image_append(plots, stack = TRUE)    # attach images in stack top to bottom

image_write(im1, 'rq.png')

联合地块

于 2017-09-22T05:55:04.280 回答
0

plot包使用的函数quantreg有它自己的 mfrow 参数。如果您没有指定它,它会强制执行它自己选择的某些选项(从而覆盖您的par(mfrow = c(2,2)).

使用mfrow内的参数plot.rqs

# make one plot, change the layout
plot(fit1, parm = 2, mfrow = c(2,1))
# add a new plot
par(new = TRUE)
# create a second plot
plot(fit2, parm = 2, mfrow = c(2,1))
于 2017-09-17T08:48:05.693 回答