最近CRAN上新了一个叫eoffice的package,并且不时被各路大佬提起。这个包的功能刚好也符合我最近的需求,这次带各位先来试试水。包的官方介绍:
1. Introductioncran.r-project.org这次主要试试在word中用该包插入ggplot。既然要试,图就整的复杂一点:
> rm(list = ls())
> gc()used (Mb) gc trigger (Mb) max used (Mb)
Ncells 2423917 129.5 4543915 242.7 4543915 242.7
Vcells 6168695 47.1 12255594 93.6 10143094 77.4
>
> pacman::p_load(data.table, magrittr, ggplot2, ggthemr, cowplot, stringr, dplyr, patchwork)
>
> library(eoffice)
> library(gridExtra)
>
> ggthemr('fresh')
>
> test<-mtcars %>% mutate(text = rownames(mtcars)) %>% data.table() %$%
+ .[,c('brand', 'model','tag'):=tstrsplit(text, split = ' ')]
> testsum<-test[,.(mpg = mean(mpg, na.rm = T), wt = mean(wt, na.rm = T)), by = 'brand'][1:5,]
>
>
> p1<-ggplot(test)+
+ geom_histogram(aes(x = mpg))+
+ coord_flip()+
+ scale_y_continuous(limits = c(0,8))+
+ annotation_custom(grob = tableGrob(testsum, rows = NULL),
+ xmin = 25, xmax = 33, ymin = 5, ymax = 7)
> p2<-ggplot(test)+
+ geom_point(aes(x = disp, y = hp))
> p3<-ggplot(test)+
+ geom_hex(aes(x = drat, y = wt))
>
> p<-p1+(p2/p3)
> p
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
出图如下:
拼图用的patchwork,如何在图中插入表格请参考我之前写的文章:传送门。
然后按照官方介绍,直接用todocx把图片插入word:
> todocx(p, filename = 'D:/R/eoffice/testword.docx', width = 6.5, height = 5,
> append = F)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Warning message:
dml_docx() is deprecated and will be removed in the next version (> 0.2.0), use devEMF::emf instead.
注意:append设置为F的话,filename文件原有的内容会被完全覆盖!第一次尝试千万注意备份文件。
提示一些警告,不过不要紧,看看filename的文件:
这么方便的工具,排版当然不可能帮你一次排好的。要自己调长宽,并且像图中有grob对象(就是那张表)的情况下,这些对象还要单独调整。
这玩意儿牛逼的地方在于,图片导出word的时候就是矢量图,所有元素都可以选中并编辑,像上图那样。但凡投过paper的都知道期刊会要求稿件里插图的矢量图,这个包在这方面可以为我们省下不少功夫。
不过这也有缺点,要是要素过多(例如大量数据的散点图),一般电脑打开这个word肯定死机。就上面那个图片,我的笔电打开word都已经有点卡了...
此外,如果导出的时候filename的文件已在word打开,就会报错:
> todocx(p, filename = 'D:/R/eoffice/testword.docx', width = 6.5, height = 5,
+ append = F)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Error in value[[3L]](cond) : Could not write "D:/R/eoffice/testword.docx" [zip error: `Cannot open zip file `D:/R/eoffice/testword.docx` for writing` in file `zip.c:373`]
此外: Warning messages:
1: In grob$wrapvp <- vp : 到达了流逝时间限制
2: dml_docx() is deprecated and will be removed in the next version (> 0.2.0), use devEMF::emf instead.
将append设置为T,就可以在已存在的文档最后面插入图片了:
> todocx(p, filename = 'D:/R/eoffice/testword_2.docx', width = 6.5, height = 5,
+ append = T)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
总的来说,eoffice无法调整导出图片为栅格(例如jpeg),因此导出到word可能是eoffice最不适用的场景了。比较建议的用法还是每张图片单独存成一个ppt或pdf。