从格子图中删除内边距

Remove inner margins from lattice plot

感谢 中的出色回答和一些进一步的想法,我可以在 ggplot 旁边绘制一个 lattice 图:

library(ggplot2)
library(lattice)
library(gtools)
library(plyr)
library(grid)
library(gridExtra)

set.seed(1)
mdat <- data.frame(x = rnorm(100), y = rnorm(100), veryLongName = rnorm(100),
                   cluster = factor(sample(5, 100, TRUE))) 
cols <- c("x", "y", "veryLongName")
allS <- adply(combinations(3, 2, cols), 1, function(r)
    data.frame(cluster = mdat$cluster,
          var.x = r[1],
          x = mdat[[r[1]]],
          var.y = r[2],
          y = mdat[[r[2]]]))

sc <- ggplot(allS, aes(x = x, y = y, color = cluster)) + geom_point() +
      facet_grid(var.x ~ var.y) + theme(legend.position = "top")
sc3d <- cloud(veryLongName ~ x + y, data = mdat, groups = cluster)

scG  <- ggplotGrob(sc)
sc3dG <- gridExtra:::latticeGrob(sc3d)
ids <- grep("axis-(l|b)-(1|2)|panel", scG$layout$name)
scG$grobs[ids[c(2, 5, 8)]] <- list(nullGrob(), nullGrob(), nullGrob())
grid.newpage()
grid.draw(scG)
pushViewport(viewport(0, 0, width = .515, height = .46,
                      just = c("left", "bottom")))
grid.rect()
grid.draw(sc3dG)

正如您在图片中看到的那样,格子图周围有相当多的边距,并且在其顶部切掉了 z 轴的轴标签(情况并非如此,我绘制了 lattice 单独绘制)。

那么我怎样才能摆脱这种行为,从而解决以下两个问题:

  1. 去掉 viewportlattice 图之间的内边距
  2. 避免 lattice 图中的标签被剪切。

我尝试使用 viewportclip 选项但没有成功。那么,怎么办?


2020 年更新

编辑代码和答案以反映 grob 中的新命名约定。

这些设置可能在 ?xyplot 的某处,但我发现它更快地阅读互联网,

theme.novpadding <-
  list(layout.heights =
         list(top.padding = 0,
              main.key.padding = 0,
              key.axis.padding = 0,
              axis.xlab.padding = 0,
              xlab.key.padding = 0,
              key.sub.padding = 0,
              bottom.padding = 0),
       axis.line = list(col = 0),
       clip =list(panel="off"),
       layout.widths =
         list(left.padding = 0,
              key.ylab.padding = 0,
              ylab.axis.padding = 0,
              axis.key.padding = 0,
              right.padding = 0))


sc3d <- cloud(veryLongName ~ x + y, data = mdat, groups = cluster,
              par.settings = theme.novpadding )

scG  <- ggplotGrob(sc)
sc3dG <- grobTree(gridExtra:::latticeGrob(sc3d), 
                  rectGrob(gp=gpar(fill=NA,lwd=1.2)))
ids <- grep("axis-(l|b)-(1|2)|panel", scG$layout$name)
scG$grobs[ids[c(5, 2, 8)]] <- list(nullGrob(), sc3dG, nullGrob())
grid.newpage()
grid.draw(scG)