Search code examples
rr-markdownbookdown

Caption above figure in html Rmarkdown


Is it possible to move the caption above my figure when knitting to HTML in RMarkdown? It seems that it is possible in PDF, ie when knitting to PDF, but I can't figure out how to replicate this for HTML. I am using bookdown to number figures.

When I run something like this:

```{r fig.cap= "caption"}
df <- data.frame(letter = letters[1:5], value = 1)

ggplot(df, aes(as(factor(1), value, fill = letters))) +
  geom_bar(stat = "identity")

```

the caption is displayed at the bottom of the figure, but I would like to display it above the figure.


Solution

  • For HTML output, you may set the chunk option fig.topcaption = TRUE to place captions above figures. Below is a minimal example (it works for both html_document and bookdown's HTML output formats):

    ---
    title: "Reprex"
    output:
      html_document: null
      bookdown::html_document2: null
    ---
    
    ```{r, fig.cap='A caption.', fig.topcaption=TRUE}
    plot(cars)
    ```
    

    Caption above the figure