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

使用xelatex批量生成带ggplot的参数化R Markdown PDF编译失败

测试代码(testing_for_stackoverflow.Rmd)
---
output: 
  pdf_document:
    latex_engine: xelatex
tables: true
graphics: yes
header-includes:
  - \\usepackage{booktabs}
  - \\usepackage{fontspec}
  - \\usepackage{graphicx}
  - \\usepackage{amsmath}
  - \\setmainfont{Times New Roman} 
  - \\newcommand{\\bcenter}{\\begin{center}} 
  - \\newcommand{\\ecenter}{\\end{center}}
params:
  cut: "Very Good"
---
\\fontsize{10}{12}
\\selectfont
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE,
                      warning = FALSE,
                      message = FALSE,
                      fig.align = 'center',
                      include = TRUE,
                      tinytex.tlmgr_update = FALSE,
                      results='asis',
                      fig.dim = c(7, 2.5))
pacman::p_load(tidyverse)

我使用diamonds数据集,cut为参数

filter(diamonds, cut == params$cut) %>%
  ggplot(aes(color, price)) +
  geom_boxplot()
kableExtra::kable(head(filter(diamonds, cut == params$cut))) 
---

# 控制台执行代码
```r
library(tidyverse)
lapply(unique(diamonds$cut), function(i) {
  rmarkdown::render(input = "testing_for_stackoverflow.Rmd",
                    params = list(cut = i),
                    rmarkdown::pdf_document(),
                    output_dir = "out/",
                    output_file = paste0(i, ".pdf"))
})

解决方案

1. 修复render()参数顺序错误

你在render()调用中遗漏了output_format参数名,直接将rmarkdown::pdf_document()放在params之后,导致参数解析错位。这会使YAML中设置的latex_engine未被正确应用,而只有生成带ggplot的PDF时,字体引擎的问题才会触发编译失败(无图时编译逻辑简单,未暴露错误)。修正后的代码:

library(tidyverse)
lapply(unique(diamonds$cut), function(i) {
  rmarkdown::render(input = "testing_for_stackoverflow.Rmd",
                    params = list(cut = i),
                    output_format = rmarkdown::pdf_document(latex_engine = "xelatex"), # 显式指定引擎
                    output_dir = "out/",
                    output_file = paste0(i, ".pdf"))
})

2. 替代fontspec设置Times New Roman的方法

若fontspec报错,可改用LaTeX原生字体包,无需依赖xelatex/lualatex(适用于纯英文文档):
修改YAML的header-includes部分:

header-includes:
  - \\usepackage{booktabs}
  - \\usepackage{graphicx}
  - \\usepackage{amsmath}
  - \\usepackage{newtxtext,newtxmath} # 替代Times New Roman的LaTeX标准包
  - \\newcommand{\\bcenter}{\\begin{center}} 
  - \\newcommand{\\ecenter}{\\end{center}}

若坚持使用xelatex,需确保系统已安装Times New Roman字体,且输出路径无特殊字符。

3. 优化带空格的输出文件名

Windows下路径空格易引发异常,可将输出文件名中的空格替换为下划线:

output_file = paste0(str_replace_all(i, " ", "_"), ".pdf")

内容的提问来源于stack exchange,提问作者Congli Zhang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:14:52