将gridExtra更新为2.0.0后使用ggsave和arrangeGrob

问题描述 投票:8回答:3

因为到目前为止我在stackoverflow上读了很多类似的问题,所以在没有将ggplot2更新到开发版本的情况下我找不到一个好的解决方案。

我的问题,我有几个脚本使用arrangeGrob从单个图形创建组合图。我将它们保存到变量和print这个变量和/或用ggsave保存。由于我的很多同事经常更新包(这是我认为的好事),我总是收到邮件后,我的脚本在更新到gridExtra 2.0.0后不再有效。

我不知道如何处理这个,因为解决问题的新ggplot2版本仍在开发中。如果要保存的对象是article,因为新的ggplot函数返回一个arrangeGrob对象,我在堆栈溢出上发现了一个gtable来删除测试,但是在我的情况下失败了:

library(ggplot2)
library(grid)
library(gridExtra)
a <- data.frame(x=c(1,2,3),
                y=c(2,3,4))
p <- ggplot(a, aes(x, y)) + geom_point()
b <- arrangeGrob(p, p)
grid.draw(b)
ggsave('test.pdf', b)
ggsave <- ggplot2::ggsave
body(ggsave) <- body(ggplot2::ggsave)[-2]
ggsave('test.pdf', b)

控制台上的一些输出和错误:

d> grid.draw(b)
d> ggsave('test.pdf', b)
Error in ggsave("test.pdf", b) : plot should be a ggplot2 plot
d> ggsave <- ggplot2::ggsave
d> body(ggsave) <- body(ggplot2::ggsave)[-2]
d> ggsave('test.pdf', b)
Saving 10.5 x 10.7 in image
TableGrob (2 x 1) "arrange": 2 grobs
  z     cells    name           grob
1 1 (1-1,1-1) arrange gtable[layout]
2 2 (2-2,1-1) arrange gtable[layout]
d> 

test.pdf已创建,但它以任何方式被破坏,无法打开。 gtable对象也被打印出来。所以我猜这里有些不对劲。

但是,正如你所看到的,我发现在示例代码中,我发现grid.draw函数至少可以绘制我的组合图,但我仍然不能在修改后使用ggsave

我不想使用pdf(file = "test.pdf"); grid.draw(b); dev.off()中建议的“旧”(this article)设备保存功能,因为它们使用起来非常不舒服。

this question,有人问到如何保存对象,但在答案他们只是解释使用grid.darw他接受答案为solving the problem,没有人回答我的评论到目前为止。

所以我现在很迷失,如何为那些已经和没有更新到新的gridExtra包的人提供工作脚本。在ggsave函数中删除测试的方法是我认为最好的解决方案,因为我可以检查gridExtraggplot2版本,只是覆盖ggsave函数,以防版本不匹配,但我无法让它运行。

期待得到一些帮助。

编辑:

也许sessionInfo有帮助

d> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] gridExtra_2.0.0 ggplot2_1.0.1  

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.1      digest_0.6.8     MASS_7.3-44      plyr_1.8.3       gtable_0.1.2    
 [6] magrittr_1.5     scales_0.3.0     stringi_1.0-1    reshape2_1.4.1   devtools_1.9.1  
[11] proto_0.3-10     tools_3.2.0      stringr_1.0.0    munsell_0.4.2    colorspace_1.2-6
[16] memoise_0.2.1  
r ggplot2 gridextra
3个回答
2
投票

作为这个不幸的过渡期的临时解决方法,您可以重新实现曾经在gridExtra中的类hack,

class(b) <- c("arrange","ggplot", class(b))
print.arrange <- function(x) grid.draw(x)
ggsave('test.pdf', b)

0
投票

Pascal最终让我想到检查ggplot 1.0.1ggplot 1.0.1.9003之间的差异,因为我不想或迫使ggplot的开发版本。

所以我的想法是一个函数,它将在每个脚本中执行,覆盖默认的ggsave函数。

我现在测试了一下,如果有任何错误,请告诉我。但是我现在这样做的方式到目前为止一直有效。

repairGgsave <- function() {
  ggplot_version <- 
    compareVersion(as.character(packageVersion('ggplot2')), 
                 '1.0.1.9003')
  gridextra_version <- 
    compareVersion(as.character(packageVersion('gridExtra')), 
                   '0.9.1')
  if(gridextra_version > 0) {
    if(ggplot_version <= 0) {
      ggsave <- function(filename, plot = last_plot(),
                         device = NULL, path = NULL, scale = 1,
                         width = NA, height = NA, units = c("in", "cm", "mm"),
                         dpi = 300, limitsize = TRUE, ...) {

        dev <- plot_dev(device, filename, dpi = dpi)
        dim <- plot_dim(c(width, height), scale = scale, units = units,
                        limitsize = limitsize)

        if (!is.null(path)) {
          filename <- file.path(path, filename)
        }
        dev(file = filename, width = dim[1], height = dim[2], ...)
        on.exit(utils::capture.output(grDevices::dev.off()))
        grid.draw(plot)

        invisible()
      }
      assign("ggsave", ggsave, .GlobalEnv)
      plot_dim <<- function(dim = c(NA, NA), scale = 1, units = c("in", "cm", "mm"),
                           limitsize = TRUE) {

        units <- match.arg(units)
        to_inches <- function(x) x / c(`in` = 1, cm = 2.54, mm = 2.54 * 10)[units]
        from_inches <- function(x) x * c(`in` = 1, cm = 2.54, mm = 2.54 * 10)[units]

        dim <- to_inches(dim) * scale

        if (any(is.na(dim))) {
          if (length(grDevices::dev.list()) == 0) {
            default_dim <- c(7, 7)
          } else {
            default_dim <- dev.size() * scale
          }
          dim[is.na(dim)] <- default_dim[is.na(dim)]
          dim_f <- prettyNum(from_inches(dim), digits = 3)

          message("Saving ", dim_f[1], " x ", dim_f[2], " ", units, " image")
        }

        if (limitsize && any(dim >= 50)) {
          stop("Dimensions exceed 50 inches (height and width are specified in '",
               units, "' not pixels). If you're sure you a plot that big, use ",
               "`limitsize = FALSE`.", call. = FALSE)
        }

        dim
      }

      plot_dev <<- function(device, filename, dpi = 300) {
        if (is.function(device))
          return(device)

        eps <- function(...) {
          grDevices::postscript(..., onefile = FALSE, horizontal = FALSE,
                                paper = "special")
        }
        devices <- list(
          eps =  eps,
          ps =   eps,
          tex =  function(...) grDevices::pictex(...),
          pdf =  function(..., version = "1.4") grDevices::pdf(..., version = version),
          svg =  function(...) grDevices::svg(...),
          emf =  function(...) grDevices::win.metafile(...),
          wmf =  function(...) grDevices::win.metafile(...),
          png =  function(...) grDevices::png(..., res = dpi, units = "in"),
          jpg =  function(...) grDevices::jpeg(..., res = dpi, units = "in"),
          jpeg = function(...) grDevices::jpeg(..., res = dpi, units = "in"),
          bmp =  function(...) grDevices::bmp(..., res = dpi, units = "in"),
          tiff = function(...) grDevices::tiff(..., res = dpi, units = "in")
        )

        if (is.null(device)) {
          device <- tolower(tools::file_ext(filename))
        }

        if (!is.character(device) || length(device) != 1) {
          stop("`device` must be NULL, a string or a function.", call. = FALSE)
        }

        dev <<- devices[[device]]
        if (is.null(dev)) {
          stop("Unknown graphics device '", device, "'", call. = FALSE)
        }
        dev
      }
    }
  }
}

它基本上覆盖了ggsave并从开发版本创建了两个新函数。

执行该功能后,一切似乎都有效。


0
投票

修复我明确定义文件:

ggsave(file='test.pdf', b)

© www.soinside.com 2019 - 2024. All rights reserved.