User 2014
User 2014

Reputation: 183

How to add subfigure in R markdown (bookdown)

I'm trying to add a figure with sub captions in a R bookdown project as follows

---
output:
  pdf_document:
    extra_dependencies: "subfig"
---
     
```{r  echo=F, out.width = "50%",fig.showtext=TRUE,fig.show='hold',fig.cap="TITULO"}
par(mfrow=c(1,2))
knitr::include_graphics("ts_mult.png") 
knitr::include_graphics("ts_ad.png") 
```

and I get the following result

enter image description here

then I tried to add the subcaptions ("imagen a", "imagen b") as follows

```{r  echo=F, out.width = "50%",fig.showtext=TRUE,fig.show='hold',fig.cap="TITULO",fig.subcap=c("imagen a", "imagen b")}
par(mfrow=c(1,2))
knitr::include_graphics("ts_mult.png") 
knitr::include_graphics("ts_ad.png") 
```

but that didn't work and it throws the following error

! Undefined control sequence.
<recently read> \subfloat 

Error: LaTeX failed to compile Tesis_AE.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips.

How can I correctly add the subcaptions?

Upvotes: 5

Views: 1538

Answers (1)

Carlos Luis Rivera
Carlos Luis Rivera

Reputation: 3633

You just need to add fig.subcap=c("A subtitle","Another subtitle") in the chunk.

In my environment, at least, fig.showtext=TRUE is not necessary and rather this causes an error: Error in loadNamespace(name) : there is no package called 'showtext' Calls: <Anonymous> ... loadNamespace -> withRestarts -> withOneRestart -> doWithOneRestart Execution halted. That's why I excluded the setting in my answer.

---
output:
  pdf_document:
    extra_dependencies: "subfig"
    keep_tex: yes
---
     
```{r echo=F, out.width = "50%",fig.show='hold',fig.cap="TITULO", fig.subcap=c("Subtitulo1","Subtitulo2")}
par(mfrow=c(1,2))
knitr::include_graphics("your-path-to/image1.png") 
knitr::include_graphics("your-path-to/image2.png") 
```

Session Info

> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=Japanese_Japan.932  LC_CTYPE=Japanese_Japan.932    LC_MONETARY=Japanese_Japan.932
[4] LC_NUMERIC=C                   LC_TIME=Japanese_Japan.932    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.0.2 tools_4.0.2   

> rmarkdown::pandoc_version()
[1] ‘2.7.3’

enter image description here

Upvotes: 7

Related Questions