2
votes

In a .Rmd document there are several ways to produce figures side-by-side. If the figures already exist, the easiest way for me is to use knitr::include_graphics(c(fig1, fig2, ...)) [Thx: Yihui!]

But when I do this, I can't find a way to add an overall figure caption, as is easily done in LaTeX. Here is an example:

chunk

```{r, out.width = "30%", echo=FALSE}
# two figs side by side
include_graphics(c("fig/mathscore-data.png",
                   "fig/mathscore-data-ellipses.png"))
```

Output:

enter image description here

If I add a fig.cap to the chunk options, I get two separate figures, each with the same figure caption.

```{r, out.width = "30%", echo=FALSE, fig.cap="Left: scatterplot of mathscore data; Right: Data ellipses for the two groups."}
# two figs side by side
include_graphics(c("fig/mathscore-data.png",
                   "fig/mathscore-data-ellipses.png"))
```

enter image description here

Is there some other way to do what I want -- two sub-figures side-by-side, with a common caption?

1
Is your output HTML or PDF or something else? What´s your YAML header? - J_F
the nice thing with rmarkdown is that you can (for pdf ) allwas fallback to latex so: - user12256545
/begin{figure} /includegraphics[ ]{ } ,etc will work. - user12256545

1 Answers

5
votes

its both possible in knitr or plain latex.

in knitr set the chunk option to:

echo=FALSE,out.width="49%",out.height="49%",fig.show='hold',

fig.align='center'

I used the latex package subcaption,

imported in the header-includes section of the YAML header.

---
title: "Untitled"
author: "V"
date: "22 4 2020"
output: pdf_document
header-includes:
  - \usepackage{subcaption}
---


# add Two figures with latex

\begin{figure}[h]
\begin{subfigure}{.5\textwidth}
\includegraphics[]{CAT.png}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\includegraphics[]{CAT.png}
\end{subfigure}
\caption{This is the main caption - Years 2020 - 2030 - the main caption. }
\end{figure}

#  add Two figures with Knitr 


```{r, echo=FALSE,out.width="49%",out.height="49%",fig.show='hold',
fig.align='center', fig.cap="This is the main caption - Years 2020 - 2030 - the main caption."}
knitr::include_graphics(c("CAT.png","CAT.png"))

enter image description here