0

The section of the bookdown manual on generating figures demonstrates a case where include_graphics() can be given a vector of paths of length > 1, producing a number of subplots with a single caption:

enter image description here

However, when I try this in my fork of thesisdown, in the PDF output I get the figure caption (and, judging by the spacing, the entire figure environment) repeated for each subplot. Here is a reproducible example:

---
output: bookdown::pdf_document2
toc: false
---


```{r, echo = FALSE}
for(i in 1:3){
  jpeg(filename = paste0("temp_", i, ".jpg"), width = 600, height = 250)
  plot(cars)
  title(main = i)
  dev.off()
}
```

```{r fig.cap = "Caption", out.width="100%", fig.ncol = 1, echo = FALSE}
knitr::include_graphics(paste0("temp_", 1:3, ".jpg"))
```

enter image description here

I was hoping more for the five images stacked, with a single caption at the bottom. This also appears to be breaking the figure cross-referencing, as each plot has its own figure number and cross-references to the chunk render as ??.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
jimjamslam
  • 1,988
  • 1
  • 18
  • 32

1 Answers1

1

Getting subfigures requires a few additional settings to be set in the chunk header.

  • fig.subcap is a list of the captions for subfigures
  • fig.ncol: the number of columns of subfigures
  • out.width: the output width of the figures. You will normally set this 100% divided by the number of sub columns.

Subfigures are built using the subfig package. You can either include this within your LaTeX bookdown template, or alternative you can added it to the YAML as follows:

Here is an example:

---
output: bookdown::pdf_document2
toc: false
header-includes:
   - \usepackage{subfig}
---

```{r, echo = FALSE}
for(i in 1:3){
  jpeg(filename = paste0("temp_", i, ".jpg"), width = 600, height = 250)
  plot(cars)
  title(main = i)
  dev.off()
}
```

```{r fig.cap = "Caption", out.width="100%", fig.ncol = 1, echo = FALSE, fig.subcap= c("First", "Second", "Third")}
knitr::include_graphics(paste0("temp_", 1:3, ".jpg"))
```

enter image description here

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Thanks, this works perfectly! Do you happen to know whether the `position` argument from `subfig1 is supported to move the subcaptions above their respective figures? I tried supplying `fig.position = 'top'` to the chunk, but no dice. – jimjamslam Mar 08 '18 at 23:24
  • 1
    You will have to probably alter the settings of the `subfig` package and add some LaTeX to the document. Check out the package here: http://mirror.ox.ac.uk/sites/ctan.org/macros/latex/contrib/subfig/subfig.pdf . If you cannot work it out might be worth making another question – Michael Harper Mar 08 '18 at 23:32
  • Passing the argument in the `usepackage` command did the trick: `\usepackage[position=top]{subfig}` – jimjamslam Mar 25 '18 at 02:15