r语言读写word_R语言:在word中插入ggplot
最近CRAN上新了一個叫eoffice的package,并且不時被各路大佬提起。這個包的功能剛好也符合我最近的需求,這次帶各位先來試試水。包的官方介紹:
1. Introduction?cran.r-project.org這次主要試試在word中用該包插入ggplot。既然要試,圖就整的復(fù)雜一點:
> 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設(shè)置為F的話,filename文件原有的內(nèi)容會被完全覆蓋!第一次嘗試千萬注意備份文件。
提示一些警告,不過不要緊,看看filename的文件:
這么方便的工具,排版當然不可能幫你一次排好的。要自己調(diào)長寬,并且像圖中有g(shù)rob對象(就是那張表)的情況下,這些對象還要單獨調(diào)整。
這玩意兒牛逼的地方在于,圖片導(dǎo)出word的時候就是矢量圖,所有元素都可以選中并編輯,像上圖那樣。但凡投過paper的都知道期刊會要求稿件里插圖的矢量圖,這個包在這方面可以為我們省下不少功夫。
不過這也有缺點,要是要素過多(例如大量數(shù)據(jù)的散點圖),一般電腦打開這個word肯定死機。就上面那個圖片,我的筆電打開word都已經(jīng)有點卡了...
此外,如果導(dǎo)出的時候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設(shè)置為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`.這是一個挺大的word文檔,里頭還有各種追蹤修訂,也順利導(dǎo)入了總的來說,eoffice無法調(diào)整導(dǎo)出圖片為柵格(例如jpeg),因此導(dǎo)出到word可能是eoffice最不適用的場景了。比較建議的用法還是每張圖片單獨存成一個ppt或pdf。
總結(jié)
以上是生活随笔為你收集整理的r语言读写word_R语言:在word中插入ggplot的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我国31个省市当中,哪个省份借的钱最多?
- 下一篇: 使用三种方式创建Class字节码类文件对