使用网格来注释绘图区域之外的格子图

using grid to annotate lattice plots outside of the plotting region

我经常使用 lattice 包来创建图形。然后我使用 grid::grid.text() 来注释绘图区域之外的图形。一般情况下,我制作的是PDF文件,没有任何问题。

我现在需要将图形保存为其他格式,例如 PNG。我现在发现,当我尝试在绘图区域之外进行注释时,注释会被剪掉。这是一个小例子:

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")))

我可以使用 gridExtra::grid.arrange() 解决这个问题,但解决简单问题的方法似乎过于复杂:

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'))

有没有更简单的方法?我有 Deepayan Sarkar 关于 lattice 的书和 Paul Murrell 的 R Graphics, 但我没有在其中找到明确的解决方案。 base graphics or ggplot 中出现该问题时,有相关的 SO 帖子,但我还没有找到关于格子图形中的问题的帖子。

您可以手动调整边距。

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")))

但由于必须手动完成,因此可能不是理想的解决方案。