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

时间:2018-12-19 11:29:51

标签: r r-markdown knitr bookdown

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)
```

2 个答案:

答案 0 :(得分:3)

可以通过插入适当的LaTeX命令来执行此操作,但我的愚见认为,输出结果看起来并不令人满意。

选项1:字幕包

通过将- \usepackage{caption}添加到标头包括中来包含字幕包,然后在字幕中使用\newline命令。

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

选项2:通过长行强制换行

添加足够的水平空白也会导致换行。但是,标题将不再显得居中。

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

有关详细信息,请参见TeX stackexchange

答案 1 :(得分:3)

您可以考虑使用子图(例如,

)来代替换行符。
---
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