1

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}

Community
  • 1
  • 1
alistair
  • 1,164
  • 10
  • 27

1 Answers1

3

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.

baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Thanks - what exactly does that do? – alistair Mar 03 '14 at 13:32
  • I think the device name is actually `postscipt` for eps output. Note you can also set the dev option for a single chunk (in its header line) if you don't want the option set globally. – Tyler Mar 03 '14 at 13:34
  • Brilliant, that has simplified things a lot! – alistair Mar 03 '14 at 13:49
  • note that many knit arguments are vectorised; you can for example give `width=c(10, 8)` to get different size png and eps output. – baptiste Mar 03 '14 at 13:53