R Notebook/Markdown 不使用 "fig.path = " 块选项保存块图

R Notebook/Markdown does not save chunk plots using "fig.path = " chunk option

我正在 运行R Notebook 中进行分析,我希望在 R 块中创建的所有绘图都保存为单独的 PDF 文件 除了 出现在 .nb.html 笔记本输出中。

问题

我遇到的问题是,当笔记本是 运行 时,它不会将图保存到块选项 fig.path = "figures/" 中指定的目录中,无论是在单独的块头中指定的:

#```{r fig.path = "figures/"}
plot(x, y)
#```

或者当使用全局块选项指定时:

#```{r setup}
library(knitr)
opts_chunk$set(fig.path = "figures/")
#```

#```{r}
plot(x, y)
#```

事实上,根本没有名为 *figures/ 的目录,。不在项目根目录中,也不在 .Rmd 脚本所在的目录中。即使我手动创建文件夹 proj_root/figures/,绘图也不会输出到这里。

我试过的

# 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/"

,我认为应该创建 project-root/figures/ 文件夹并在那里输出所有块图,除了将它们保存在 .nb.html 报告中。

我也尝试过在 opts_chunk$set(dev = "pdf", fig.path = "figures/") 的全局块选项中指定 dev = "pdf",但这并没有改变任何东西。

我不知道我做错了什么,在我搜索过的所有地方,none 个选项都有效,包括:

knitr documentation 没有帮助,因为它只描述了 fig.path = 块选项,但如果它不起作用则无法进行故障排除。我是否需要添加其他 fig.*** = 块选项才能使其工作?它不应该只设置 fig.path = 选项吗?

这与我的 YAML 输出是 html_notebook 而不是输出到 markdown 或 html_document 有什么关系吗?

最接近 post 我遇到的问题是这个:R Notebook: Include figures in report and save plots,但自 2018 年以来一直没有解决,我不确定如何 'promote' post 除了制作一个新的并引用它。

我进行了测试,fig.path 选项按预期工作。请测试以下 rmd:

Edit:确保在Rmd YAML header中设置输出类型为output: html_document,同时点击Knit to HTML激活保存数字。这与 运行 Rmd 文档是分开的,并且可以在 Run All 之后以交互方式或与 Run All 一起完成。 请参阅下面的评论

---
title: "Untitled"
author: "TC"
date: "10/30/2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.path="testit/")
```

## R Markdown



```{r pressure, echo=FALSE}
plot(pressure)
```

```{r pressure2, echo=FALSE}
plot(pressure)
```


```{r echo=FALSE}
plot(pressure)
```

rmd source

here is the generated figures under testit