Caption at the top of the image. Option from chunk rmardown

Viewed 128

Can you set the caption option on a chunk that generates a graph in rmarkdown?

When we use a caption as the title of a graphic generated in a code fragment (chunk), a latex output is generated for .pdf that includes the caption under the graphic. I have read the documentation and I cannot find a way to configure the latex output where caption is defined before the graphic image.

1. UPGRADE


{r, echo=FALSE, eval=TRUE, fig.cap="CAPTION", fig.pos="H"}

2 Answers

You should use \captionof from package{caption}

---
title: "R Notebook"
header-includes:
- \usepackage{caption}
- \usepackage{graphicx}
output:
  pdf_document: default
---

\captionof{figure}{Text of the caption.}
```{r, echo=FALSE}
library(ggplot2)

k <- ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point() + 
    theme(plot.margin = unit(c(0,0,0,0), "cm"))     
k
```
\centering
\captionof{figure}{Text of the caption.}
\includegraphics{your_pic.png}

enter image description here

Package "float" is used with kable and kableExtra.

When we need to place the caption of a figure at the top the only solution I have found is to use the "floatrow" package.

Since "float" and "floatrow" are incompatible, it is necessary to add some additional configurations in "floatrow" so that the appearance of the tables generated with kable and kableExtra using rstudio, rmarkdown and knitr is identical.


header-includes:
 - \usepackage{floatrow}
 - \floatsetup[figure]{capposition=top} % Caption figure top.
 - \floatsetup[table]{capposition=top} % Caption table top.
 - \floatplacement{figure}{H} % Figure position according to the code flow.
 - \floatplacement{table}{H} % Table position according to the code flow.
 - \floatsetup[longtable]{margins=centering} % Longtable tables centered.

Related