grid.newpage() conflicts with plot.new()

68 Views Asked by At

I am following this example to make a base graphics plot rotated 45 degrees. Now I came to a situation when I need to call grid.newpage() to basically clear the grid's viewport tree, but I also need to call plot.new() so that I can plot the plot title. But if I call both, I will get an extra blank page on the pdf device:

pdf(file = "trialD1.pdf", width = 7, height = 7) 

{ # this code belongs to my custom function, which should work for any device
dev <- dev.cur()
dev.new() # auxilliary device

plot(1,1)

library(gridGraphics) # solution to rotate 45 deg - https://stackoverflow.com/a/32198964/684229
grid.echo() # redraws it without reason, no matter what I try (invisible(), x = NULL, newpage = FALSE)
g <- grid.grab() # again redraws it without reason... even with invisible() 
dev.off() # closes auxilliary device

dev.set(dev) # need to come back to the device that was active before, because dev.off() could skip it (https://stackoverflow.com/q/77426629/684229)
grid.newpage()
plot.new() # so that title() can work 
pushViewport(viewport(width = 0.7072, height = 0.7072, angle=45))
grid.draw(g)
title(main = "Hello world", cex.main = 2)
} # end of function

dev.off() # pdf

I just wanted to get one page pdf with the plot displayed on the second page, which looks like this:

enter image description here

WARNING: If I remove grid.newpage(), it looks like it works, but for pdf only; if we e.g. use it for Windows plotting device multiple times, it will start to behave erroneously since the viewports keep stacking as the viewport tree didn't get cleared with grid.newpage(). So, looks like grid.newpage() is kind of a "reset" function for the grid stuff that needs to be called when new image is drawn. Or, one needs some replacement for it...

0

There are 0 best solutions below