Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 526
Bjørn Kallerud Avatar asked Jul 10 '19 21:07

Bjørn Kallerud


2 Answers

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

like image 194
Yihui Xie Avatar answered Sep 23 '22 08:09

Yihui Xie


You can do that, but if you set echo = TRUE, the caption will appear above the code...

---
title: "Untitled"
author: "Stéphane Laurent"
date: "29 février 2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::knit_hooks$set(htmlcap = function(before, options, envir) {
  if(before) {
    paste('<p class="caption">', options$htmlcap, "</p>",sep="")
  }
})
```

```{r, echo = FALSE, htmlcap="Hello Dolly"}
library(ggplot2)
ggplot(diamonds,aes(price,carat)) + geom_point()
```
like image 44
Stéphane Laurent Avatar answered Sep 22 '22 08:09

Stéphane Laurent