我正在 R Notebook 中运行分析,我希望将在 R block 中创建的所有绘图保存为单独的 PDF 文件除了出现在.nb.html 笔记本输出。
问题
我遇到的问题是,当笔记本运行时,它不会将图保存到 block 选项 fig.path = "figures/"
中指定的目录中单独的 block 头:
#```{r fig.path = "figures/"}
plot(x, y)
#```
或者当使用全局 block 选项指定时:
#```{r setup}
library(knitr)
opts_chunk$set(fig.path = "figures/")
#```
#```{r}
plot(x, y)
#```
事实上,根本没有名为*figures/
的目录任何地方。不在项目根目录中,也不在 .Rmd 脚本所在的目录中。即使我手动创建文件夹 proj_root/figures/
,绘图也不会输出到这里。
我尝试过的
- 我尝试为将图输出到
fig.path = "figures/"
的单个 block 设置 block 选项,这不会产生任何内容 - 在设置 block 中,我运行了这些行:
# 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/
文件夹并在那里输出所有 block 图,除了将它们保存在 .nb.html 报告中。
我还尝试在 opts_chunk$set(dev = "pdf", fig.path = "figures/") 的全局 block 选项中指定
,但这并没有改变任何东西。dev = "pdf"
我不知道自己做错了什么,而且在我搜索过的所有地方,没有一个选项有效,包括:
- 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
knitr documentation没有帮助,因为它仅描述了 fig.path =
block 选项,但如果它不起作用则无法进行故障排除。我是否需要添加其他 fig.*** =
block 选项才能使其工作?它不应该只设置 fig.path =
选项吗?
这与我的 YAML 输出是 html_notebook
而不是输出到 markdown 或 html_document
有什么关系吗?
我遇到的最接近我的问题的帖子是这个:R Notebook: Include figures in report and save plots ,但它自 2018 年以来一直没有得到解决,除了制作新帖子并引用它之外,我不确定如何“推广”该帖子。
最佳答案
我进行了测试,fig.path 选项按预期工作。请测试以下 rmd:
编辑:确保在Rmd YAML header中将输出类型设置为output: html_document
,同时点击Knit to HTML
即可激活数字的保存。这与以交互方式或使用 Run All
运行 Rmd 文档是分开的,并且可以在之后完成。
请参阅下面的评论
---
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
https://stackoverflow.com/questions/58600399/how-do-you-run-an-r-file-on-ubuntu?noredirect=1#comment103544013_58600399
```{r pressure, echo=FALSE}
plot(pressure)
```
```{r pressure2, echo=FALSE}
plot(pressure)
```
```{r echo=FALSE}
plot(pressure)
```
关于R Notebook/Markdown 不使用 "fig.path = " block 选项保存 block 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58598873/