R:如何将基本绘图保存到网格对象,grid.echo()除外
背景:我使用了包R:如何将基本绘图保存到网格对象,grid.echo()除外,r,plot,grid,R,Plot,Grid,背景:我使用了包MatchIt(一个倾向评分匹配包)中的包装plot函数,发现很难将图形放在一个页面上 我的解决方案是:首先将绘图转换为网格对象(使用grid.echo和grid.grab从gridGraphicspackage抓取),然后使用grid.arrangementfromgridExtrapackage对其进行排列 问题:使用grid.echo时,出现错误:“单位错误(x,默认的.units):“x”和“units”的长度必须大于0” 我发现这是因为图形的一部分包含所有FALSE值。
MatchIt
(一个倾向评分匹配包)中的包装plot
函数,发现很难将图形放在一个页面上
我的解决方案是:首先将绘图转换为网格对象(使用grid.echo
和grid.grab从gridGraphics
package抓取),然后使用grid.arrangement
fromgridExtra
package对其进行排列
问题:使用grid.echo
时,出现错误:“单位错误(x,默认的.units):“x”和“units”的长度必须大于0”
我发现这是因为图形的一部分包含所有FALSE
值。与其尝试破解grid.echo
函数或plot
函数,我想问一下是否有其他方法将基本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
###生成数据和模型
种子(10)
df两个图表可以通过par()
函数组合成一个输出文件,而无需将图形转换为其他对象类型。在这个场景中,我们将使用par(mfrow=c(1,2))
来指示base R graphics在一行中写入两个绘图。使用原始帖子中的示例代码,我们生成如下图
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()
set.seed(10)
谢谢你的回答和例子。我确实意识到,par(mfrow())
可以做到这一点,但问题实际上来自添加其他类型的绘图。例如,par(mfrow=c(1,2))
,plot(m.out,type='jitter')
,plot(m.out,type='QQ')
将有问题。这是因为MatchIt
包中的plot
函数将几个绘图打包在一起,因此在调用plot(…,type='QQ')
时,它将覆盖par(mfrow())
。很抱歉在可复制代码中出现混乱。我应该使用plot(…,type='QQ')
。如果MatchIt正在覆盖par()
,则应报告为缺陷。有关报告MatchIt中的缺陷的说明,请访问。如果其他人在grid.echo中遇到类似问题,请参阅:Paul Murrell在github版本的gridGraphics中修复了该缺陷。