I often use the lattice package to create figures. I then use grid::grid.text()
to annotate the figures outside of the plotting region. Typically, I make PDF files, and there are no problems.
I now need to save my figures in other formats, like PNG. And I now find that when I try to annotate outside of the plotting region, the annotations are clipped. Here is a small example:
library(grid)
library(gridExtra)
library(lattice)
myPanel <- function (...) {
panel.xyplot(...)
grid.text("This is a very, very long line", x = .99, y = .5)
}
xyplot(1:10 ~ 1:10, panel = myPanel, par.settings = list(clip = list(panel="off")))
I can get around this problem by using gridExtra::grid.arrange()
, but it seems like a too-elaborate way to solve a simple problem:
myPlot_grob <- grid.grab(wrap = TRUE)
rectTransparent <- rectGrob(gp = gpar(col = 'transparent', fill = 'transparent'))
grid.arrange(
grobs = list(
rectTransparent,
myPlot_grob,
rectTransparent),
ncol = 3,
widths = unit(c(2, 4, 2), 'inches'))
Is there a simpler way? I have both Deepayan Sarkar's book on lattice and Paul Murrell's R Graphics, but I haven't found a clear solution in them. There are related SO posts for the problem when it comes up in base graphics or ggplot, but I haven't found posts that speak to the issue in lattice graphics.
You can manually adjust the margin padding.
lattice.options(layout.widths=list(left.padding=list(x=0), right.padding=list(x=5)))
xyplot(1:10 ~ 1:10, panel = myPanel, par.settings = list(clip = list(panel="off")))
But since it has to be done manually, it may not be an ideal solution.