Export Graph in R, and also display it in knitr

落爺英雄遲暮 提交于 2019-12-11 09:16:15

问题


I'm using knitr and want my rmd file to generate an eps file in a figures/ folder whenever it's run. I found this question: Export a graph to .eps file with R which does what I want, but doesn't display the charts in the webpage produced by knitr, presumably because the postscript command just routes anything drawn to the file you give it. I would like to display a graph AND save it to the file. Currently my code is something like:

```{r}
setEPS()
postscript("~/File/Path/To/Figures/Folder/Figure.eps")
par(mar=c(4, 4, 4, 10))
barplot(prop.table(t(testtable[2:4]), 2), names=testtable$Group, legend=c(colnames(testtable)[2:4]), args.legend=list(x=7, y=1), xlab="Groups", ylab="Percentage of Answers")
dev.off()
``` 

In knitr, this produces

## pdf 
##   2

I would have to run the same bar plot command after dev.off() to produce anything in knitr.

I can think of two strategies: 1) Route graphics to both the file and knitr. 2) Save the r commands as a variable and run whatever the variable contains before and after dev.off().

I'm not sure how to do either of those.


It turned out there was a 3) Get knitr to save the plot as eps. I didn't like doing that because the files were saved as unnamed_chunk_x.png and I wanted them named. It turns out if you can name them by editing the {r} ->{r name-of-your-chart}


回答1:


I would do this,

opts_chunk$set(dev=c('png','postscript'))

to produce two versions of each figure automatically (one png, one eps). As @Tyler commented, you can also do it on a chunk-by-chunk basis rather than a global option.



来源:https://stackoverflow.com/questions/22147594/export-graph-in-r-and-also-display-it-in-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!