R:除了grid.echo()之外,如何将基础图保存到网格对象

时间:2018-01-06 08:22:48

标签: r plot grid

背景:我使用了包plot(一个倾向评分匹配包)中的包裹MatchIt函数,并发现将图表放在一起的困难。

我的解决方案:首先将图表转换为网格对象(使用grid.echo包中的grid.grabgridGraphics),然后使用grid.arrange中的gridExtra打包安排。

问题:使用grid.echo时,会出现错误:“单位错误(x,default.units):'x'和'units'的长度必须为> 0”。

我发现这是因为图表的一部分具有所有FALSE值。我想询问是否有另一种方法可以将grid.echo保存为plot个对象,而不是试图破解base plot函数或grobs函数?

这是一个可重复性最小的例子:

### Generate data and the model
set.seed(10)
df <- data.frame(y=sample(c(0,1),20,replace=TRUE),x1=rnorm(20),x2=1:20)
library(MatchIt)
m.out <- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="treat") 
### This one is OK because "discard" is set, so that the plot has none empty values in all parts    
m.out_none <- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="none") 
### This one is NOT OK because "discard" is not set, so part of the plot is empty.

### function to convert base plot to grid objects
library(gridGraphics)
grab_grob <- function(){
    grid.echo()
    grid.grab()
}

plot(m.out_none,interactive=FALSE,type='jitter')
p1 <- grab_grob() ### Error here
plot(m.out,interactive=FALSE,type='jitter')
p2 <- grab_grob() ### No errors

1 个答案:

答案 0 :(得分:1)

可以使用par()功能将两个图表组合成单个输出文件,而无需将图形转换为其他对象类型。在这种情况下,我们将使用par(mfrow=c(1,2))指示基础R图形在一行中写入两个图。使用原始帖子中的示例代码,我们生成如下图形。

set.seed(10)
df <- data.frame(y=sample(c(0,1),20,replace=TRUE),x1=rnorm(20),x2=1:20)
library(MatchIt)
m.out <- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="treat")     
m.out_none <- matchit(y~x1+x2,data=df,method='nearest',replace=TRUE,ratio=2,discard="none") 
# configure an output file to which the charts will be written
thePngFile <- png(file="matchit.png",width=960,height=480,units = "px")
# configure output file with 1 row and 2 columns
par(mfrow=c(1,2))
plot(m.out_none,interactive=FALSE,type='jitter')
title(sub="out_none")
plot(m.out,interactive=FALSE,type='jitter')
title(sub="out")
dev.off()

代码生成以下输出文件。

enter image description here

请注意,如果以这种方式将图表指定为R Markdown文档的一部分,则不需要额外的输出文件。 R将在输出文档中的一个图中呈现两个图表。