grid.grab()
captures all of the current viewports and stores them as a grob. In theory, and often in practice, you can use grid.grab()
to store an image now for drawing later on. But I have noticed some odd behavior of grid.grab()
when working with lattice output. It is related to the wrap
argument:
wrap = TRUE
, the saved grob should produce a drawing faithful to the original viewports. But sometimes it doesn't.wrap = TRUE
, grid.grab()
warns me to use wrap = TRUE
.Here is a minimal example to illustrate these behaviors:
library(grid)
library(lattice)
xyplot(1:5 ~ 1:5)
trellis.focus()
panel.abline(h = 3)
panel.abline(h = 5)
myGrob <- grid.grab(wrap = TRUE)
At this point, I receive a warning—
In grabDL(warn, wrap, ...) :
one of more grobs overwritten (grab WILL not be faithful; try 'wrap = TRUE')
—which is strange, given that I specified wrap = TRUE
.
I proceed by running
grid.newpage()
grid.draw(myGrob)
According to Paul Murrell (R Graphics, 2nd ed., page 239), using grid.grab(wrap = TRUE)
is "guaranteed to replicate the original output." But it doesn't. Specifically, the top horizontal line (from panel.abline(h = 5)
) isn't reproduced.
I've run this example in R 3.3.2 and 3.5.1. It comes out the same in both cases. Are these bugs, or am I overlooking something?
Paul Murrell answered the question on the R-help mailing list. In short, the problem arises because, in the example above, the code creates two grobs with the same name, which in turn causes problems with grid.grab()
. In his answer, Paul suggests that one workaround is to name the second grob: replace
panel.abline(h = 5)
with
panel.abline(h = 5, identifier = "abline2")
and there are no problems. (I've verified that this solution works.) Paul also notes that a coming version of grid.grab()
will be better able to handle cases like the one that I described above.