Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figure captions with multiple plots in one chunk

I label my figures like this.

---
title: "xxx"
output: 
  pdf_document:
    fig_caption: true
---

And then in each chunk

```{r, fig.cap="some caption"}
qplot(1:5)
```

This works quite nicely. However in chunks where I plot multiple figures within a loop I can't specify a caption. This produces no caption at all:

```{r, fig.cap="another caption"}
qplot(1:5)
qplot(6:10)
```

How can I specify a figure that counts from the same number as the first chunk for each plot?

like image 372
sbstnzmr Avatar asked Dec 19 '16 20:12

sbstnzmr


2 Answers

You can use a fig.cap argument of length 2 (or the size of your loop):

```{r, fig.cap=c("another caption", "and yet an other")}
qplot(1:5)
qplot(6:10)
```
like image 196
scoa Avatar answered Oct 30 '22 03:10

scoa


Found an easy way to dynamically produce plots and add them to the pdf with individual captions, using knitr::fig_chunk as described here. This is also a workaround for OPs comment that message=false (or echo=False or results='asis' for that matter) supresses the fig.cap argument.

```{r my-plots, dev='png', fig.show='hide', echo=FALSE}
# generate plots first
qplot(1:5)
qplot(6:10)
```

```{r, echo=FALSE, results='asis'}
# then put them in the document with the captions
cat(paste0("![some caption](", fig_chunk(label = "my-plots", ext = "png", number = 1), ")\n\n"))
cat(paste0("![another caption](", fig_chunk(label = "my-plots", ext = "png", number = 2), ")\n\n"))
```

Hopefully this helps someone who stumbles upon this question in the future.

like image 1
bubble Avatar answered Oct 30 '22 04:10

bubble