从格子图中删除内边距

标签 r ggplot2 lattice

感谢"Combine a ggplot2 object with a lattice object in one plot"中的出色回答还有一些进一步的想法,我可以绘制 lattice ggplot 旁边的图:

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. 去掉 viewport 之间的内边距和 lattice情节
  2. 避免 lattice 中的标签剧情被删减。

我尝试玩 clip viewport 的选项但没有成功。那么,该怎么办?

<小时/>

2020 年更新

编辑代码和答案以反射(reflect) grob 中的新命名约定。

enter image description here enter image description here

最佳答案

这些设置可能位于?xyplot中,但我发现阅读互联网速度更快,

enter image description here

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)

关于从格子图中删除内边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332580/

相关文章:

r - 基于 R 中的单个数据集生成许多多图

R 中 iGraph 的 random_walk 函数不会停止在吸收状态

r - 根据单独的列值删除每行的列

r - 如果匹配定义的长度则更改 NA 值

r - 如何整齐地对齐堆叠条形图标签,使条形的每一侧对齐方式不同?

r - 我不知所措 - ggplot2::ggsave 不会导出自定义字体

r - 在 R 中渲染 Rmarkdown 停止时创建可执行的 ShinyApp 后

r - 在 R lattice xyplot 上分别控制 Axis 刻度和轴线

R格子: How to add empty plots with border to fill the gaps of defined layout

r - 无法标记点图中的点