在R中,当使用gridBase在图中嵌入子图时,如何防止pdf中的空白页

时间:2022-08-18 11:51:10

As explained here, it is easy to embed a plot into an existing one thanks to gridBase, even though both plots use the base graphics system of R. However, when saving the whole figure into a pdf, the first page is always blank. How to prevent this?

正如这里所解释的那样,由于gridBase很容易将一个绘图嵌入现有的绘图中,即使两个绘图都使用了R的基本图形系统。但是,当将整个图形保存为pdf时,第一页始终为空白。怎么预防这个?

Here is an example:

这是一个例子:

require(gridBase)

## generate dummy data
set.seed(1859)
x <- 1:100
y <- x + rnorm(100, sd=5)
ols <- lm(y ~ x)

pdf("test.pdf")

## draw the first plot
plot.new() # blank page also happens when using grid.newpage()
pushViewport(viewport())
plot(x, y)

## draw the second plot, embedded into the first one
pushViewport(viewport(x=.75,y=.35,width=.2,height=.2,just=c("center","center")))
par(plt=gridPLT(), new=TRUE)
hist(ols$residuals, main="", xlab="", ylab="")
popViewport(2)

dev.off()

2 个解决方案

#1


23  

I think it's a bit of a hack but setting onefile=FALSE worked on my machine:

我认为这有点像黑客但设置onefile = FALSE在我的机器上工作:

pdf("test.pdf", onefile=FALSE)

In searching for an answer (which I didn't really find so much as stumbled upon in the forest) I came across this post to Rhelp from Paul Murrell who admits that mixing grid and base graphics is confusing even to the Master.

在寻找答案时(我在林中偶然发现并没有那么多)我从Paul Murrell那里得到了这篇文章给Rhelp,他承认混合网格和基础图形甚至让主人感到困惑。

#2


0  

A work around solution I found was to initiate the pdf file inside the for loop; then insert an if clause to assess whether the first iteration is being run. When the current iteration is the first one, go ahead and create the output device using pdf(). Put the dev.off() after closing the for loop.

我找到的解决方案是在for循环中启动pdf文件;然后插入一个if子句来评估是否正在运行第一次迭代。当前迭代是第一次迭代时,继续使用pdf()创建输出设备。关闭for循环后放置dev.off()。

#1


23  

I think it's a bit of a hack but setting onefile=FALSE worked on my machine:

我认为这有点像黑客但设置onefile = FALSE在我的机器上工作:

pdf("test.pdf", onefile=FALSE)

In searching for an answer (which I didn't really find so much as stumbled upon in the forest) I came across this post to Rhelp from Paul Murrell who admits that mixing grid and base graphics is confusing even to the Master.

在寻找答案时(我在林中偶然发现并没有那么多)我从Paul Murrell那里得到了这篇文章给Rhelp,他承认混合网格和基础图形甚至让主人感到困惑。

#2


0  

A work around solution I found was to initiate the pdf file inside the for loop; then insert an if clause to assess whether the first iteration is being run. When the current iteration is the first one, go ahead and create the output device using pdf(). Put the dev.off() after closing the for loop.

我找到的解决方案是在for循环中启动pdf文件;然后插入一个if子句来评估是否正在运行第一次迭代。当前迭代是第一次迭代时,继续使用pdf()创建输出设备。关闭for循环后放置dev.off()。