4

I'm using an R Notebook and I'd like my plots to automatically save to disk when the code is run, as well as display inline.

knitr: include figures in report *and* output figures to separate files addresses this for R Markdown but the solution given doesn't work for an R Notebook. Is there a similar option for R Notebooks?

Lauren Fitch
  • 346
  • 4
  • 12

2 Answers2

0

Try setting the knitr fig.path option:

knitr::opts_chunk$set(fig.path = "path/to/figures/")

Where path/to/figures/ is the path to a subdirectory where your figures will be saved. The trailing slash is necessary. This should be a relative path, either relative to the RNotebook file or to the project directory. See here::here() for a handy way to locate the project directory.

This will put each figure into that directory; figure names will be based on the chunk name (so name your chunks!)

DonJ
  • 923
  • 11
  • 18
  • 1
    This didn't work for me. The plot displays in the saved notebook HTML file but there is no plot saved into the specified folder. – Lauren Fitch Mar 23 '18 at 19:06
  • I also tried setting it directly within the chunk but that didn't work either: ````{r test, fig.path="/figs/"} hist(iris$Sepal.Length) ```` – Lauren Fitch Mar 23 '18 at 19:24
  • Try `{r test, fig.path="figs/"}`. Currently you're creating a top-level directory under /. – DonJ Mar 26 '18 at 13:13
  • Hi, thanks for the suggestion, however, that doesn't work either. Nothing is saved to the `"figs/"` sub-directory. – Lauren Fitch Mar 26 '18 at 15:30
  • How could you specify the figure driver to use? Such a jpeg or pdf? – user29609 Jun 12 '18 at 21:27
  • You specify that using the `dev` chunk option: `opts_chunk$set(dev = 'png')`. You can also specify multiple devices, for example: `opts_chunk$set(dev = c('pdf', 'png')` will generate PDF and PNG versions of each plot. – DonJ Jun 13 '18 at 11:59
0

This is what eventually worked for me (see @TCZhang 's answer to my question here):

In addition to setting the knitr chunk fig.path="figures/" option suggested by @DonJ, try setting output: html_document, or just press the dropdown next to the Preview [Notebook] button at the top and press Knit to HTML. I think the reason this isn't working is that your output is set to output: html_notebook.

I don't know why this doesn't work specifically when the doc is in R Notebook format. I would also prefer if this worked for output: html_notebook, so it might be an issue we need to open with RStudio or knitr.

Leo
  • 187
  • 1
  • 9