2017-09-17 98 views
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的对象作为陈述here
  3. 使用功能layout函数试图在this文件
  4. 我试图寻找到的plot.rqs的源代码。但我无法理解它是如何绘制置信区间(我只能绘制分位数的系数),或者在那里改变参数。

有人可以指出我哪里错了吗?我应该查看plot.rqs的源代码并更改其中的参数吗?

回答

1

虽然quantreg::plot.summary.rqsmfrow参数,它使用它来覆盖par('mfrow'),以便面向parm值,这不是你想要做的。

一种替代方法是解析对象并手动绘制。您可以将tau值和coeffi cient矩阵出fit1fit2,这只是每个头值的列表,所以在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` 

facetted plot

拉多出来的对象,如果你喜欢,添加水平原来的线条,否则就会疯狂。


另一种选择是使用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(p1p2, stack = TRUE) # attach images in stack top to bottom 

image_write(im1, 'rq.png') 

joined plots

+0

这工作得很好,尽管我现在无法破译代码。感谢这个出路。 – Enigma

+0

我编辑了一些评论,加上更直接的'magick'方法。 – alistaire

0

quantreg软件包使用的函数plot它拥有自己的mfrow参数。如果不指定,它强制它而选择在它自己的一些选项(从而覆盖您的par(mfrow = c(2,2))

使用内plot.rqsmfrow参数:

# 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)) 
+0

我尝试这样做。但是当我增加mfrow的维度时(因为我有更多的变量,比如我在OP中展示的变量),所以他们不会按顺序绘制。在'mfrow = c(2,2)'中,第一个绘图出现在左上角(Grid - 1,1),第二个绘制在右下(Grid - 2,2),第三个绘制在(2,2) 。 – Enigma