9

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?

2 Answers 2

16

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)
```
6
  • 1
    Thanks. This works perfectly in a sample. Even better I can combine them in a previous chunk with a loop feeding my names list.
    – sbstnzmr
    Dec 20, 2016 at 14:08
  • actually, you can even set it in the same chunk if you use eval.after='fig.cap' yihui.name/knitr/options/#package_options
    – scoa
    Dec 20, 2016 at 14:10
  • Thanks Stackoverflow for automatically posting when hitting enter and then not letting me edit my comment. The important part of the above comment ist missing: This works perfectly in a sample. Even better I can combine them in a previous chunk with a loop feeding my names list. Unfortunately this does only work in a sample and not in my actual document with 26 names in the loop
    – sbstnzmr
    Dec 20, 2016 at 14:11
  • Found the error. In the chunk I had message=FALSE cause the loop produces ## geom_smooth() using method = 'loess' for each item in the loop. The message=false also seem to suppress the figure caption. So is there another way that I can get rid of the message?
    – sbstnzmr
    Dec 20, 2016 at 14:53
  • I think you need to ask another question with a MCVE
    – scoa
    Dec 20, 2016 at 15:13
2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.