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

标签 r r-markdown knitr chunks rnotebook

我正在 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 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)
```

rmd source

here is the generated figures under testit

关于R Notebook/Markdown 不使用 "fig.path = " block 选项保存 block 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58598873/

相关文章:

R:将矩阵列表中的0更改为NA的更简单方法?

r - 如何在 ggplot2 中添加 abline,x 轴为年份?

jquery - 如何放大 Rmarkdown 演示文稿中的绘图

r - 使用 knit 和 pandoc 转换为 PDF 时 Markdown 中的图形位置

r - 在苏门答腊 PDF 阅读器中打开编译的 .rnw 的自定义函数?

r - glm eval 中的错误(family$initialize): y values must be 0 <= y <= 1 BUT values ARE 0 and 1

r - 长度参数无效

r - 在knitr中指定多个同时输出格式(新)

r - 国际化 R knitr 图标题标签

r - 使用 knitr::include_graphics 将图像插入 RMarkdown 时的替代文本?