0

目前,我正在尝试绘制一个数据集,其中刻面数量为奇数,在图中留下不完整的最后一行。理想情况下,我希望每个不完整的最后一行和上面的行下方的 x 轴标签,其中底行是空的。

我已经审查了这个问题和答案,这似乎正是我想要的。但是,似乎自从上次更新此答案以来, ggplot 或 gridExtra 中的某些内容发生了变化,在尝试使用ggsave. 代码不是创建有效文件,而是将结构打印TableGrob到控制台(包含在更下方)并生成损坏的 4KB PDF 文件(无法在 OS X 上通过 QuickLook、Preview 或 Adob​​e Reader 打开)。

我尝试使用的代码如下,我相信它与原始链接答案中的代码相匹配:

library(ggplot2)
library(grid)

facetAdjust <- function(x, pos = c("up", "down"))
{
  pos <- match.arg(pos)
  p <- ggplot_build(x)
  gtable <- ggplot_gtable(p); dev.off()
  dims <- apply(p$panel$layout[2:3], 2, max)
  nrow <- dims[1]
  ncol <- dims[2]
  panels <- sum(grepl("panel", names(gtable$grobs)))
  space <- ncol * nrow
  n <- space - panels
  if(panels != space){
    idx <- (space - ncol - n + 1):(space - ncol)
    gtable$grobs[paste0("axis_b",idx)] <- list(gtable$grobs[[paste0("axis_b",panels)]])
    if(pos == "down"){
      rows <- grep(paste0("axis_b\\-[", idx[1], "-", idx[n], "]"), 
        gtable$layout$name)
      lastAxis <- grep(paste0("axis_b\\-", panels), gtable$layout$name)
      gtable$layout[rows, c("t","b")] <- gtable$layout[lastAxis, c("t")]
    }
  }
  class(gtable) <- c("facetAdjust", "gtable", "ggplot"); gtable
}

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) + 
facet_wrap(~ color)

d <- facetAdjust(d)
ggsave("test.pdf",d)

运行时,这会产生以下控制台输出:

Saving 7 x 7 in image
TableGrob (16 x 13) "layout": 33 grobs
    z         cells       name                                    grob
1   0 ( 1-16, 1-13) background          rect[plot.background.rect.239]
2   1 ( 4- 4, 4- 4)    panel-1                 gTree[panel-1.gTree.53]
...(shortened)...
32 31 ( 4-12,12-12)  guide-box                       gtable[guide-box]
33 32 ( 2- 2, 4-10)      title               text[plot.title.text.237]

...并且还会生成一个 4KB 的 PDF 文件,该文件无法通过 QuickLook、Preview 或 Adob​​e Reader 打开。

我已尽我所能审查了 facetAdjust 功能,但经验不足,无法确定问题所在。有人对如何解决此问题有任何建议吗?

4

1 回答 1

0

相当愚蠢,但是在调试另一个问题时删除了打印功能,并且没有正确恢复它。正如baptiste建议的那样,添加以下函数可以解决问题:

print.facetAdjust <- function(x, newpage = is.null(vp), vp = NULL) {
  if(newpage)
    grid.newpage()
  if(is.null(vp)){
    grid.draw(x)
  } else {
    if (is.character(vp)) 
      seekViewport(vp)
    else pushViewport(vp)
    grid.draw(x)
    upViewport()
  }
  invisible(x)
}
于 2014-12-15T14:53:01.937 回答