knitr/Rmarkdown: 如何让多张图片并排显示并只有一个标题

9
.Rmd文档中,有几种方法可以并排生成图形。如果图像已经存在,则对我来说最简单的方法是使用knitr::include_graphics(c(fig1, fig2, ...)) [感谢:Yihui!]
但是当我这样做时,我找不到一种添加总体图标题的方法,就像在LaTeX中轻松完成的那样。 以下是一个示例: 代码块
```{r, out.width = "30%", echo=FALSE}
# two figs side by side
include_graphics(c("fig/mathscore-data.png",
                   "fig/mathscore-data-ellipses.png"))
```

输出:

enter image description here

如果我在代码块选项中添加fig.cap,我会得到两个单独的图形,每个图形都有相同的图形标题。
```{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

有没有其他方法可以实现我想要的效果——将两个并排的子图放在一起,并且有一个共同的标题?


你的输出是HTML,PDF还是其他格式?你的YAML头部信息是什么? - J_F
RMarkdown 的好处在于,对于 PDF 格式,你总是可以回退到 LaTeX。 - user12256545
/begin{figure} /includegraphics[ ]{ } 等等都可以工作。 - user12256545
仅供参考 https://bookdown.org/yihui/rmarkdown-cookbook/figures-side.html - Yihui Xie
1个回答

13

在knitr或纯LaTeX中都可以实现。

knitr中,将块选项设置为:

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

我使用了latex的子标题包subcaption,

在YAML头部的header-includes一节中导入。

---
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"))
 

这里输入图像描述


1
谢谢 @J_F,我缺少的是 fig.show="hold" 用于 HTML 输出。 - user101089
有没有办法在这两个图像下面得到一个(a)和(b)或类似的东西? - Felix Jassler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接