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

Rmd输出PDF时Plotly多图并排未关闭LaTeX figure环境问题

你遇到的问题是plotly包的knitr打印逻辑和rmarkdown的PDF输出流程不兼容导致的:plotly输出到PDF时需要先将交互式图表转为静态栅格图,该转换过程没有正确识别knitr的fig.show='hold'、fig.ncol等多图布局参数,因此无法自动生成完整的figure环境闭合标签与图题。

以下是3种经过验证的可行解决方案:

方案1:将plotly转为静态图片后调用,复用基础绘图的布局逻辑

该方案无需调整绘图逻辑,也不用手动写LaTeX代码,只需要提前把plotly对象导出为临时图片,再用knitr::include_graphics加载即可,原有代码块的fig.cap、fig.ncol等参数完全生效。

先安装依赖包:

install.packages(c("webshot2", "htmlwidgets"))
# webshot2会自动调用系统安装的Chrome/Edge/Chromium浏览器做静态渲染

替换原有Plotly代码块内容即可:

```{r echo=FALSE, message=FALSE, results=FALSE, fig.show='hold', fig.ncol=2, fig.cap = "Plot caption goes here.", out.width="0.46\\textwidth"}
library(plotly)
# 生成plotly对象
p1 <- plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = 'scatter', mode = 'markers')
p2 <- plot_ly(cars, x = ~speed, y = ~dist, type = 'scatter', mode = 'markers')
# 导出为临时png
tmp1 <- tempfile(fileext = ".png")
tmp2 <- tempfile(fileext = ".png")
htmlwidgets::saveWidget(p1, tempfile(fileext = ".html"))
webshot2::webshot(tempfile(fileext = ".html"), file = tmp1, vwidth = 600, vheight = 500)
htmlwidgets::saveWidget(p2, tempfile(fileext = ".html"))
webshot2::webshot(tempfile(fileext = ".html"), file = tmp2, vwidth = 600, vheight = 500)
# 加载图片,自动适配布局
knitr::include_graphics(c(tmp1, tmp2))
---
## 方案2:用plotly::subplot直接生成带独立图例的组合图
如果不想导出静态图,也可以通过调整subplot的图例参数实现每个子图保留独立图例,不需要依赖knitr的多图布局逻辑:
```r
```{r echo=FALSE, message=FALSE, results=FALSE, fig.cap = "Plot caption goes here.", out.width="0.9\\textwidth"}
library(plotly)
p1 <- plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = 'scatter', mode = 'markers', name = "鸢尾花数据") %>%
  layout(legend = list(x = 0, y = 1.1)) # 调整第一个图例位置到左上角
p2 <- plot_ly(cars, x = ~speed, y = ~dist, type = 'scatter', mode = 'markers', name = "车速数据") %>%
  layout(legend = list(x = 0.6, y = 1.1)) # 调整第二个图例位置到右上角
# 生成两列布局的组合图,不共用坐标轴、不隐藏图例
subplot(p1, p2, nrows = 1, shareX = FALSE, shareY = FALSE, titleX = TRUE, titleY = TRUE)
---
## 方案3:手动编写LaTeX的figure环境
如果不想调整绘图逻辑,也可以关闭代码块的自动图题生成,手动补全LaTeX标签,直接在Rmd中插入原生LaTeX环境即可:
```tex
\begin{figure}
\centering
```{r echo=FALSE, message=FALSE, results=FALSE, out.width="0.46\\textwidth"}
plotly::plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = 'scatter', mode = 'markers')
plotly::plot_ly(cars, x = ~speed, y = ~dist, type = 'scatter', mode = 'markers')

\caption{Plot caption goes here.}
\label{fig:plotly-combine}
\end{figure}

---
以上三个方案均可正常生成闭合的figure环境,不会出现字面LaTeX代码残留的问题。

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

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

最近更新时间:2026.09.26 04:45:05