Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to prevent blank page in pdf when using gridBase to embed subplot inside plot

Tags:

plot

r

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?

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()
like image 637
tflutre Avatar asked Sep 18 '12 16:09

tflutre


2 Answers

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

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.

like image 179
IRTFM Avatar answered Oct 01 '22 09:10

IRTFM


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. An quick example follows:

for(i in 1:5){
  if (i == 1) pdf(file = "test.pdf")
  plot(rnorm(50, i, i), main = i)}
dev.off()
like image 22
James Silva Avatar answered Oct 01 '22 10:10

James Silva