到目前为止,由于我在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
绘制。我不想使用this article中建议的“旧”(
pdf(file = "test.pdf"); grid.draw(b); dev.off()
)设备保存功能,因为它们使用起来非常不舒服。在this question中,有人确切地询问了如何保存对象,但是在回答中,他们只是解释使用
grid.darw
,他接受了答案作为solving the problem
,到目前为止,没有人回答我的评论。因此,我现在很茫然,如何为那些已经更新和尚未更新到新的
gridExtra
包的人提供有效的脚本。我猜想删除ggsave
函数中的测试的方法是最好的解决方案,因为我可以检查gridExtra
和ggplot2
版本,并在版本不匹配的情况下覆盖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
最佳答案
作为这个不幸的过渡时期的临时解决方法,您可以重新实现以前在gridExtra中使用的类hack,
class(b) <- c("arrange","ggplot", class(b))
print.arrange <- function(x) grid.draw(x)
ggsave('test.pdf', b)
关于r - 将gridExtra更新为2.0.0后使用ggsave和rangingGrob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823361/