Search code examples
rr-markdownknitrbookdown

How to get a newline in a figure caption in Rmarkdown bookdown pdf:document2


I'm using knitr in RStudio to write an rmarkdown bookdown:pdf:document2 document. I have two plots, plotted side-by-side with gridExtra, and labelled A and B. I want to put a newline in the output of the figure caption, as defined with fig.cap, between the caption for A and that for B, but I am stumped. I have tried:

\n - ignored as if it was not there

\\n - undefined control sequence

\\\n - Argument of @tempf has an extra }.

\\\\n - prints "\n" (getting a bit silly here)

double space - does nothing

I even tried, out of desperation, HTML style newlines, which I can't figure out how to display here, but I didn't expect them to work and they didn't.

It's possible in LaTeX so surely there is a way...

NOTE: this is not a duplicate of Split r chunk header across lines in knitr as that is asking how to split a long caption in a chunk header across lines in the code, and I am asking how to do so in the output.

Susannah

---
title: "MRR captions"
author: "Susannah Cowtan"
date: "14 December 2018"
output:
  bookdown::pdf_document2:
    citation_package: natbib
    number_sections: no
    toc: no
    keep_tex: true
  bookdown::html_document2: null
header-includes: 
- \usepackage{float}
- \usepackage{booktabs}
fontsize: 11pt
papersize: A4
---

```{r knitr_setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r plot-mtcars, fig.height = 3, fig.width = 4, fig.cap = "A: foo bar baz \nB: foobar"}
plot(mpg ~ wt, data = mtcars)
```

Solution

  • Instead of a newline, you may consider using sub-figures, e.g.

    ---
    title: "MRR captions"
    author: "Susannah Cowtan"
    date: "14 December 2018"
    output:
      bookdown::pdf_document2:
        keep_tex: true
    header-includes:
      - \usepackage{subfig}
    ---
    
    See Figure \@ref(fig:plot-cars), which contains Figure \@ref(fig:plot-cars1) and Figure \@ref(fig:plot-cars2).
    
    ```{r plot-cars, fig.height = 3, fig.width = 4,, out.width='49%', fig.cap='Two plots', fig.subcap = c('foo bar baz', 'foobar')}
    plot(mpg ~ wt, data = mtcars)
    plot(cars)
    ```
    

    Sub-figures