在grid.arrange中生成的空白区域

时间:2016-06-20 16:39:12

标签: r gridextra r-grid

我需要为一个人物安排几个情节。我正在使用基础和网格图形创建单独的图。为了将它们排列在一个图中,我一直使用grid.echo()grid.grab()转换为grobs,然后arrangeGrob()grid.arrange()来构建最终数字。几个星期前,我的初步数字工作正常,但现在当我重新运行代码时,它会产生一个图形边缘有空白的图形。

我添加了一个显示我面临的问题的最小例子......

##minimal example
library(grid)
library(gridExtra)
library(gridGraphics)
##test plot
plot_n1<-plot(1:10,1:10, asp=1)

##convert test plot to grob
grid.echo()
test_p<-grid.grab()

##simulate several plots arranged in a more complex layout
multi<-arrangeGrob(test_p, test_p, test_p, test_p, ncol=1, heights=c(1/4,1/4,1/4,1/4))

##create graph
png(filename="minimal_multiplot.png", res=300, width=20, height=20, units="cm")
grid.arrange(test_p, multi, ncol=2, widths=c(2/3,1/3))
dev.off()

我做错了什么?

1 个答案:

答案 0 :(得分:0)

graphics绘图转换为grid绘图时,确实会出现问题,然后使用grid.grab()抓取然后将绘图绘制到较小的区域(即使用你的方法)。例如,使用视口定义稍小的区域(下图中的灰色),轴材料缺失。

# Packages
library(grid)
library(gridGraphics)

plot(1:10,1:10)

grid.echo()
test_p = grid.grab()

grid.newpage()
pushViewport(viewport(x = 0, width = .85, just = "left"))
grid.rect(gp = gpar(col = NA, fill = "grey90"))
grid.draw(test_p)
upViewport()
grid.rect(gp = gpar(col = "grey90", size = .1, fill = NA))

enter image description here

但Paul Murrell(gridGraphics包的作者)提供了另一种选择(参见?gridGraphics::grid.echo的例子和The gridGraphics package in The R Journal v7/1的第156-157页)。可以定义绘制绘图的函数,然后在视口中绘制绘图时该函数将成为grid.echo()的参数。 newpage = FALSE阻止grid打开新页面。请注意,没有任何轴材料被切断。

pf = function() {
   plot(1:10,1:10)
}

grid.newpage()
pushViewport(viewport(x = 0, width = .85, just = "left"))
grid.rect(gp = gpar(col =NA, fill = "grey90"))
grid.echo(pf, newpage=FALSE)
upViewport()
grid.rect(gp = gpar(col = "grey90", size = .1, fill = NA))

enter image description here

所以为了得到你想要的情节,我会做这样的事情 - 但仍然使用视口。

pf = function() {
par(mar=c(7.2, 7.2, 1, 1), mex = .3, tcl = .15, mgp = c(3, .15, 0))
plot(1:10, 1:10, cex.axis = .75, cex.lab = .75)
}

grid.newpage()

pushViewport(viewport(layout = grid.layout(3, 2, 
      widths = unit(c(2, 1), "null"),
      heights = unit(c(1, 1, 1), "null"))))

pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1:3))
grid.echo(pf, newpage = FALSE)
upViewport()

for(i in 1:3) {
pushViewport(viewport(layout.pos.col = 2, layout.pos.row = i))
grid.echo(pf, newpage = FALSE)
upViewport()
}

upViewport()
grid.rect(gp = gpar(col = "grey90", size = .1, fill = NA))

enter image description here