caption multiple plots in a single chunk in r markdown

Viewed 39

I need a single code chunk in r markdown (pdf output) to generate multiple plots and caption them, but nothing seems to be working. I tried the suggested fig.cap=c("caption1","caption2") but nothing happened, there's no caption at all. How do I manage that? Here's the code. (For some reason it's not showing the tics, they're there)

---
header-includes:
  - \usepackage[croatian]{babel}
  - \pagenumbering{gobble} 
output:
  pdf_document:
    latex_engine: pdflatex 
    number_sections: true
    fig_caption: yes 
fontsize: 12pt
---

```{r, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```  

```{r slika2,fig.height=3.5,fig.cap=c("kutijasti dijagram varijable age", "kutijasti dijagram dobi osoba sa srčanom bolesti")}
par(mfrow=c(1,2))
boxplot(age,col="pink")
boxplot(age[target=="1"],col="pink")
```

enter image description here

1 Answers

Maybe you wanted to add the captions for subfigures. If so, specify fig.subcap in the R chunk and \usepackage{subfig} in header-includes.

As @shafee has already pointed out here, par(mfrow=c(1,2)) in the chunk slika2 merges two boxplot() into a single plot instead of two distinct figures. You may need to avoid using par(mfrow=c(1,2)).

---
header-includes:
  - \usepackage[croatian]{babel}
  - \pagenumbering{gobble}
  - \usepackage{subfig} ## <- Add this
output:
  pdf_document:
    latex_engine: pdflatex 
    number_sections: true
    fig_caption: yes 
fontsize: 12pt
---

```{r, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```  

```{r slika2, fig.height = 3.5, fig.cap = "My figures", fig.subcap = c("kutijasti dijagram varijable age", "kutijasti dijagram dobi osoba sa srčanom bolesti"), out.width="50%"}
#par(mfrow = c(1, 2))
boxplot(mtcars, col = "pink")
boxplot(mtcars[mtcars$cyl == "6",], col = "pink")
```

enter image description here

Related