6.6 LaTeX sub-figures

Sometimes you may want to include multiple images in a single figure environment. Sub-figures allow us to achieve this by arranging multiple images within a single environment and providing each with its own sub-caption.

Sub-figures require the LaTeX package subfig. We can load it via the extra_dependencies YAML option within the pdf_document output. For example:

  1. ---
  2. output:
  3. pdf_document:
  4. extra_dependencies: "subfig"
  5. ---

To arrange all plots from a code chunk in sub-figures, you have to use the chunk options fig.cap (the caption for the whole figure environment) and fig.subcap (a character vector of the captions for sub-figures). For best output, you can also use the following options:

  • fig.ncol: The number of columns of sub-figures. By default, all plots are arranged in a single row. You can break them into multiple rows.

  • out.width: The output width of individual plots. You will normally set this to 100% divided by the number of columns. For example, if you have two plots, the out.width option should be equal to or less than 50%, otherwise the plots may exceed the page margin.

Below is an illustrative example:

  1. ---
  2. output:
  3. pdf_document:
  4. extra_dependencies: "subfig"
  5. ---
  1. ```{r, fig.cap='Figure 1', fig.subcap=c('(a)', '(b)', '(c)')}
  2. plot(1:10)
  3. plot(cars, pch = 19)
  4. boxplot(Sepal.Width ~ Species, data = iris)
  5. ```

The output is shown in Figure 6.2. For the sake of simplicity, we omitted a few chunk options in the chunk header of the above example, including fig.ncol = 2, out.width = "50%", fig.align = "center", and the actual long captions.

An example of one figure environment containing multiple sub-figures.

FIGURE 6.2: An example of one figure environment containing multiple sub-figures.