HTML 中的 Knitr 和图说明

Knitr and Figure Caption in HTML

knitr 将参数 fig.cap 定义为

fig.cap: (NULL; character) figure caption to be used in a figure environment in LaTeX (in \caption{}); if NULL or NA, it will be ignored, otherwise a figure environment will be used for the plots in the chunk (output in \begin{figure} and \end{figure})

然而,对于 HTML 输出以下作品:

---
title: "Caption Test"
author: "Some Author"
date: "February 18, 2016"
output: html_document
---

```{r}
library(ggplot2)
```

```{r, fig.cap = c("This is caption 1", "This is caption 2")}
## Plot 1
qplot(carat, price, data = diamonds)

## Plot 2
qplot(carat, depth, data = diamonds)
```

意思是,每个数字都有其在代码块参数中定义的正确标题 fig.cap = c("Caption 1", "Caption 2")

但是,当字幕被放置在块选项中时,跟踪字幕是一项挑战 - 特别是如果很长的话。除了为每个图形创建两个单独的块并在块外插入标题外,还有其他选择吗?

您可以设置 eval.after="fig.cap",以便在 块 运行 之后 评估图形标题。这样,您就可以在块内定义字幕。

---
title: "Caption Test"
author: "Some Author"
date: "February 18, 2016"
output: html_document
---

```{r}
library(ggplot2)
library(knitr)
opts_knit$set(eval.after = 'fig.cap')
```

```{r, fig.cap = cap}
## Plot 1
qplot(carat, price, data = diamonds)
cap <- "This is caption 1"

## Plot 2
qplot(carat, depth, data = diamonds)

cap <- c(cap, "This is caption 2")
```