如何将 TableGrob 对象保存到文件

How to save TableGrob object to file

我有一个 TableGrob 对象:

library(ggplot2)
library(gridExtra)
d <- data.frame(x=1:5,y=11:15)
p <- ggplot(d) + aes(x=x,y=y) + geom_point()
g <- arrangeGrob(p,p,ncol=1)

plot(g) 将按预期绘制两个相同的图,排列在一列中。

当我尝试将其保存到文件时:

ggsave('a.pdf',g)

我得到的只是一个空文件 a.pdf 和以下输出:

Saving 7 x 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]

我的问题是:如何将 TableGrob 对象保存到 pdf 文件?

以防万一,这里是 sessionInfo() 输出:

sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)

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] stats     graphics  grDevices utils     datasets  grid      methods   base     

other attached packages:
[1] gridExtra_2.2.1 dplyr_0.4.3     plyr_1.8.3      ggplot2_2.1.0   reshape_0.8.5   gdata_2.17.0    lattice_0.20-33

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.5        gtools_3.5.0       digest_0.6.9       assertthat_0.1     R6_2.1.2           gtable_0.2.0      
 [7] DBI_0.4-1          magrittr_1.5       scales_0.4.0       labeling_0.3       RColorBrewer_1.1-2 tools_3.3.0       
[13] munsell_0.4.3      parallel_3.3.0     colorspace_1.2-6  

奇怪...我从 ggsave('a.pdf', g) 得到了预期的输出。 你确定你没有在某处打错字..?一般来说,我使用这个 hack 将 tableGrob 保存为 PDF:

qplot(1:10, 1:10, geom = "blank") + theme_bw() + 
  theme(line = element_blank()) + 
  annotation_custom(grob = tableGrob(d), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)

> sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.4 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

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

other attached packages:
[1] gridExtra_2.2.1 ggplot2_2.1.0  

loaded via a namespace (and not attached):
 [1] labeling_0.3     colorspace_1.2-6 scales_0.4.0     plyr_1.8.4      
 [5] tools_3.3.0      gtable_0.2.0     Rcpp_0.12.5      grid_3.3.0      
 [9] munsell_0.4.3    tcltk_3.3.0     

我无法真正理解这个问题或其后续问题,但也许这对某人有意义

library(gridExtra)
d <- data.frame(x=1:5,y=11:15)
g <- tableGrob(d)
ggplot2::ggsave('a.pdf',g)