3

I was wondering how I could get my captions to appear above my figures in R Markdown.

Here is a working example:

---
title: "Practical"
output:
  pdf_document:
    fig_caption: yes
    latex_engine: xelatex
---

```{r fig1, echo=FALSE, fig.cap="\\label{fig:fig1}Caption"}
x <- 1:10
y <- 11:20
plot(x, y)
```

The question has been asked before here, but the code suggested does not seem to work for me.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • 1
    This will depend on the output format. Please provide a [minimal working example](https://stackoverflow.com/help/mcve) that will compile and render in your intended format (e.g., pdf, html, docx). – r2evans Mar 06 '18 at 22:38
  • Related: https://stackoverflow.com/questions/22335542/knitr-figure-captions-above?rq=1 – neilfws Mar 06 '18 at 22:44
  • After answering this question, I realised it was largely duplicated by the other post which was previously posted. I have modified my answer and reposted it there. – Michael Harper Apr 04 '18 at 19:32

1 Answers1

6

When RMarkdown is run, it converts the base document to a LaTeX document using pandoc. As a result, we LaTeX packages can be used within the document, which can help in achieving advance customisation like this.

In this case, the Floatrow package can be used to reposition the caption above the figure. This is largely based of this previous answer. It can be loaded by including header-includes argument within the YAML, as follows:


title: "Practical"
output:
  pdf_document:
    fig_caption: yes
    latex_engine: xelatex
header-includes:
   - \usepackage{floatrow}
   - \floatsetup[figure]{capposition=top}
---


```{r fig1, echo=FALSE, fig.cap="\\label{fig:fig1}Caption"}
x <- 1:10
y <- 11:20
plot(x, y)
```

enter image description here

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • I think putting `\usepackage{floatrow}` and `\floatsetup[figure]{capposition=top}` in the `preamble.tex` file of a bookdown template would be functionally equivalent, and possibly preferred if `header-includes` is passed to all output formats? – Mark Neal Mar 17 '20 at 03:05
  • 1
    Yes, you could use either approach, as explained here: https://bookdown.org/yihui/rmarkdown-cookbook/latex-preamble.html . If I have lots of code in my preamble, I tend to make a separate file of it. Not that when you say `passed to all output formats` specifying LaTeX packages will only work for PDF outputs, as Word and HTML do not use LaTeX when compiling. Hope that helps – Michael Harper Mar 17 '20 at 16:25