16

Not only would I like my figures to appear in my knitr-generated report, but I would also like to output them to separate files, too. To do this, I have included code like the following:

```{r}
  #Plot figure in report
  plot(x,y)

  #Plot figure in file
  pdf(file="MyFig.pdf")
  plot(x,y)
  dev.off()
```

This works fine, but I expect there's a more elegant solution for this already built into knitr. Is there a chunk option or something similar that achieves the same results?

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
Dan
  • 11,370
  • 4
  • 43
  • 68

3 Answers3

23

Use the option self_contained: no if you are using html_document, or keep_tex: yes if you use pdf_document, so that rmarkdown will not remove the figure files after rendering the output document.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
9

Keyword dev='pdf' as explained by Yihui here http://yihui.name/knitr/options/

Together with other options I have found useful:

```{r 'setup', echo = FALSE, cache = FALSE}
    opts_chunk$set(dev = c('pdf', 'png'), 
        fig.align = 'center', fig.height = 5, fig.width = 8.5, 
        pdf.options(encoding = "ISOLatin9.enc")) 
```
PatrickT
  • 10,037
  • 9
  • 76
  • 111
  • 4
    I use `output: html_document` most of the time, and putting `'png'` first in the list made the html render nicely and saved the figures as well. In combination with `fig.path`, `fig.width`, and `fig.height`, I was able to come up with a decent solution.: `{r plot_stuff, fig.width=10, fig.height=5, fig.path='figures/', dev=c('png', 'pdf')}` – Lance Feb 07 '17 at 21:23
  • 1
    This is really nice, keeping the hmtl document self-contained, while saving the figures from that same report as separate figures, too. @Yihui's answer above seems to me to also yield separate figures, but an html file that depends on that folder for its figures, which is often a pain when sharing reports. – 4rj4n Apr 29 '19 at 09:24
0

Try this to save the figures as files: https://www.njtierney.com/post/2018/02/28/three-r-tips/

"Tip number 1: Save the images that you create"

Barry DeCicco
  • 251
  • 1
  • 7