PGF 后端与 Overleaf 在线编译联动流程?
解读
面试官想知道你是否能把 Matplotlib 的 PGF 后端 当成“LaTeX 打印机”来用,并解决国内两大痛点:
- 本地没有完整 TeX Live 环境时,如何一键生成可被 Overleaf 直接编译的 .pgf 或 .tex 文件;
- 在 Overleaf 服务器(位于海外,且为沙箱容器)里,如何零报错地复现中文、系统字体、自定义包依赖。
回答必须体现你对 Matplotlib 后端管线、pgf.preamble、LuaLaTeX/XeLaTeX 选择、Overleaf 文件上传策略、字体回退机制 的闭环理解,否则会被视为“只会画折线”。
知识点
- PGF 后端本质:matplotlib.backends.backend_pgf,通过内存管道把 figure 转译成 PGF/TikZ 矢量指令,不依赖本地弹窗。
- 双模式输出:
–.pgf纯矢量文件,\input{}插入主文档,适合多图复用;
–.tex自包含文件,自带\documentclass{standalone},可直接编译预览。 - preamble 注入:
plt.rcParams["pgf.preamble"]可追加\usepackage{ctex}、\setCJKmainfont{SimSun}等,解决中文; - Overleaf 编译链:默认 pdfLaTeX,必须显式切换成 XeLaTeX 或 LuaLaTeX 才能识别系统字体;
- 字体可见性:Overleaf 容器仅自带 TeX Live 原始字体,需把 Windows 的 simsun.ttc、Times.ttf 等上传至项目根目录,并通过
fc-list语法在 preamble 里\setmainfont{Times.ttf}[Path=./]; - 缓存与 ID:PGF 文件含大量
\definecolor{mplcolor1}{rgb}{0.121,0.466,0.705},若 Overleaf 报“TeX memory exceeded”,需在主文档加\usepackage{luatexbase}并提升main_memory; - CI 联动:国内 GitHub/GitLab 镜像仓 push → Overleaf v2 Git 同步 → 触发
latexmk -xelatex,实现“代码-绘图-论文”三端同步。
答案
-
本地 Python 端
a) 安装依赖:pip install matplotlib>=3.7;无需本地 TeX,因为 PGF 后端只负责生成 TikZ 代码。
b) 统一 rc 参数:import matplotlib as mpl mpl.use("pgf") mpl.rcParams.update({ "pgf.texsystem": "xelatex", # 与 Overleaf 侧保持一致 "pgf.preamble": "\n".join([ r"\usepackage{ctex}", # 中文 r"\setCJKmainfont{SimSun.ttf}[Path=./]", # 把字体文件随 repo 上传 r"\usepackage{amsmath}", r"\usepackage{siunitx}" ]), "font.family": "serif", "figure.figsize": (5.5, 3.5), # 双栏宽度 "figure.dpi": 300 })c) 画图并双输出:
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0, 1], [0, 1], label="示例") ax.set_xlabel(r"时间 $\si{\second}$") ax.legend() fig.savefig("figure.pgf") # 主文档 \input{figure.pgf} fig.savefig("figure.tex") # 可选,本地快速预览d) 把
figure.pgf、SimSun.ttf、Times.ttf一并 git push 到国内 Gitee 仓库(加速 Overleaf 拉取)。 -
Overleaf 端
a) 新建项目 → 从 Git 导入 Gitee 地址(若网络受限,可手动 zip 上传)。
b) 在 Overleaf 设置里把 Compiler 改为 “XeLaTeX”,TeX Live 版本选 2022+。
c) 主文档main.tex头部加入:\documentclass[UTF8]{ctexart} \usepackage{graphicx} \usepackage{pgf} % 必须 \input{pgfplotscompat} % 若用 pgfplots \setmainfont{Times.ttf}[Path=./] \setCJKmainfont{SimSun.ttf}[Path=./]d) 插入图:
\begin{figure}[htbp] \centering \input{figure.pgf} \caption{Matplotlib 生成的高清矢量图} \end{figure}e) 若出现 “TeX capacity exceeded”,在
latexmkrc文件加$xelatex = 'xelatex -interaction=nonstopmode --shell-escape --extra-mem-bot=10000000 %O %S';f) 点击 Recompile,PDF 无字体缺失、中文正常、线条 100 % 矢量,流程闭环。
拓展思考
- CI 加速:用 GitHub Actions 国内镜像 +
overleaf/github-sync实现 PR 级预览,每改一次图 30 秒内在 Overleaf 看到结果。 - 字体子集化:若投稿期刊限制文件大小,可用
fonttools pyftsubset把 SimSun 子集化,仅保留 3500 常用汉字,将 18 MB 字体压到 800 KB。 - GPU 后端对比:PGF 是纯 CPU 生成,若图含 10 万点以上,可先用 “Agg” 后端渲染为 PDF,再
pdf2svg转矢量,兼顾速度与体积。 - Overleaf Server Pro 私有化:国内高校可自建 Overleaf 集群,把字体、企业模板预装到 Docker 镜像,学生端无需上传字体,实现“开箱即绘”。