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

Matplotlib PGF后端用LuaLaTeX报错:找不到DejaVuSerif字体

解决Matplotlib PGF后端配合LuaLaTeX时的Fontspec错误

问题根源

Matplotlib的PGF后端在使用LuaLaTeX作为编译引擎时,会自动加载fontspec宏包并尝试默认使用DejaVuSerif字体,哪怕你没有手动添加fontspec或指定该字体。这就和你通过preamble加载的newtxtext/newtxmath字体包产生了冲突,导致报错。而切换到pdflatex时,因为pdflatex不支持fontspec,Matplotlib会使用传统TeX字体加载逻辑,所以能正常工作。

解决方案

在Matplotlib的配置参数中添加pgf.fonttype = 42,这个参数会强制Matplotlib使用传统TeX字体设置方式,绕过fontspec的自动加载逻辑,和你指定的newtx字体包兼容。

修改后的代码如下:

import matplotlib as mpl
mpl.use("pgf")
preamble = r'\usepackage{newtxtext,newtxmath}'
mpl.rcParams.update({
    "pgf.texsystem": 'lualatex',
    "pgf.preamble": preamble,
    'text.latex.preamble': preamble,
    'text.usetex': True,
    'font.size': 9,
    'lines.markersize' : 3,
    # 添加这一行,强制使用传统TeX字体逻辑
    'pgf.fonttype': 42
})

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4.5, 2.5))
ax = fig.gca()
ax.plot(range(5))
ax.set_xlabel(u"µ is not $\\mu$")
fig.tight_layout()
fig.savefig("test.pdf")

补充说明

  • pgf.fonttype=42对应传统TeX字体模式(Type 42字体),适合配合pdflatex/LuaLaTeX下的传统字体包使用;
  • 如果需要使用fontspec自定义字体,可以在preamble中显式加载fontspec并指定字体,但这样需要确保字体在系统中存在,且和newtx系列字体兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:37:46