如何将TableGrob对象保存到文件中

时间:2016-06-08 16:12:41

标签: r ggplot2 gridextra

我有一个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  

2 个答案:

答案 0 :(得分:1)

很奇怪......我从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)

enter image description here

> 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     

答案 1 :(得分:0)

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

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

enter image description here