Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knitr and Figure Caption in HTML

knitr defines the argument fig.cap as

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})

However, for HTML output the following works:

---
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)
```

meaning, each figures gets its correct caption defined in the code chunk argument fig.cap = c("Caption 1", "Caption 2")

However, it is challenging to keep track of captions -especially if long- when they are placed inside the chunk options. Besides creating two separate chunks for each figure with captions inserted outside of the chunk, are there other options?

like image 731
Thomas Speidel Avatar asked Dec 25 '22 09:12

Thomas Speidel


1 Answers

You can set eval.after="fig.cap" so that figure captions are evaluated after the chunk is run. That way, you can define your captions inside the chunk.

---
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")
```
like image 117
scoa Avatar answered Dec 28 '22 07:12

scoa