You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Markdown中缩小图注与图片之间的间距?

解决R Markdown图片与图注间距过大的方案

针对HTML输出的方法

行内CSS快速调整

直接在图片语法中添加行内样式控制底部边距:

![Legend of the figure.\label{fig3}](image.pdf){width=90% style="margin-bottom: -12px;"}

调整-12px的数值,负数会缩小图片与图注的间距,按需增减即可。

全局CSS统一设置

创建一个CSS文件(例如custom.css),添加以下内容:

.figure img {
  margin-bottom: -15px;
}

然后在R Markdown的YAML头部引入该文件:

---
output:
  html_document:
    css: custom.css
---

针对PDF输出的方法

使用knitr代码块参数调整

改用knitr::include_graphics函数插入图片,并通过out.extra参数添加LaTeX命令缩小间距:

```{r fig3, fig.cap="Legend of the figure.", out.width="90%", out.extra='\\vspace{-0.6cm}', echo=FALSE}
knitr::include_graphics("image.pdf")
调整`-0.6cm`的数值来控制间距大小。

### 全局LaTeX模板修改
自定义LaTeX模板,添加`caption`包设置全局图注间距:
1. 新建一个`.tex`模板文件(例如`template.tex`),在导言区加入:
```latex
\usepackage{caption}
\captionsetup[figure]{skip=5pt} % 调整skip值控制间距
  1. 在R Markdown的YAML头部指定模板:
---
output:
  pdf_document:
    template: template.tex
---

通用方法:使用knitr代码块替代原生图片语法

无论输出格式是HTML还是PDF,都可以用knitr代码块插入图片,通过对应参数控制间距,这种方式更灵活可控:

```{r fig3, fig.cap="Legend of the figure.", out.width="90%", echo=FALSE}
knitr::include_graphics("image.pdf")
- HTML输出时,可在代码块中加`fig.extra='style="margin-bottom: -10px;"'`
- PDF输出时,加`out.extra='\\vspace{-0.5cm}'`

内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:01:07