I'm running an analysis in an R Notebook and I would like all plots created in R chunks to be saved as individual PDF files in addition to appearing in the .nb.html notebook output.
The problem
The problem I'm having is that, when the notebook is run, it does not save plots to the dir specified in the chunk option fig.path = "figures/"
either when specified in the individual chunk header:
#```{r fig.path = "figures/"}
plot(x, y)
#```
or when specified with the global chunk options:
#```{r setup}
library(knitr)
opts_chunk$set(fig.path = "figures/")
#```
#```{r}
plot(x, y)
#```
In fact, there is no dir named *figures/
at all, anywhere. not in the project root directory nor in the dir where the .Rmd script is located. Even when I manually create the folder proj_root/figures/
, plots are not output to here.
What I've tried
- I tried setting the chunk options for a single chunk that outputs a plot to
fig.path = "figures/"
, which does not produce anything - In a setup chunk, I've run these lines:
# load knitr package
library(knitr)
# set all subsequent chunks' working dir as the project root dir
opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
# set this first setup chunk working dir to project root dir (since the previous line does not affect the chunk it's run in)
setwd(rprojroot::find_rstudio_root_file())
# Check current working dir
getwd() # CORRECTLY OUTPUTS R.PROJECT ROOT DIR
# Set all chunks to output plots to the dir "figures/"
opts_chunk$set(fig.path = "figures/") # This should output all chunk plots to "project-root/figures/"
, which I assume should make the project-root/figures/
folder and output all chunk plots there, in addition to keeping them in the .nb.html report.
I've also tried also specifying dev = "pdf"
in the global chunks option in opts_chunk$set(dev = "pdf", fig.path = "figures/")
, but this doesn't change anything.
I have no idea what I'm doing wrong, and everywhere I've searched, none of the options work, including:
- Knitr with R Markdown
- knitr Documentation: Options: Plots
- knitr: include figures in report and output figures to separate files
- change where rmarkdown saves images generated by r code
The knitr documentation is unhelpful as it only describes the fig.path =
chunk option, but no troubleshooting if it doesn't work. Do I need to add other fig.*** =
chunk options in order to make it work? Shouldn't it work with only setting the fig.path =
option?
Does it have anything to do with my YAML output being html_notebook
instead of outputting to markdown or html_document
?
The closest post to my problem I have come across is this one: R Notebook: Include figures in report and save plots, but it has not been resolved since 2018 and I'm not sure how to 'promote' that post other than making a new one and referencing it.
ggsave()
. – TC Zhangset self_contained: false
? bookdown.org/yihui/rmarkdown/… – TC Zhang