Matplotlib+pgf后端(lualatex)字体显示异常,如何修复?
问题:Matplotlib PGF后端(LuaLaTeX)字体显示异常
我在使用pgf后端绘图时出现了字体显示不规则的问题。
import matplotlib.pyplot as plt import numpy as np x = np.arange(-3,3,0.1) def f(x): return x**3 plt.style.use(['seaborn-v0_8-darkgrid', 'seaborn-v0_8-dark-palette']) plt.rcParams.update({ 'font.family': 'sans-serif', 'font.size': 12, 'pgf.texsystem': 'lualatex', 'pgf.preamble': r'\usepackage{unicode-math,fontspec}\setmathfont{STIX Two Math}\setsansfont{Inter}[Scale=0.88]', 'pgf.rcfonts' : False }) plt.plot(x,f(x)) plt.title('Cubic Function') plt.xlabel('Input data ($x$)') plt.ylabel('Output data ($f(x)$)') plt.tight_layout() plt.savefig('plot_style.pdf', backend='pgf')
我的Inter字体已安装在~/.fonts目录,系统为Fedora 37。请问该问题产生的原因是什么?如何才能修复字体显示异常?
补充:若将pgf.texsystem参数改为pdflatex,并将pgf.preamble改为\usepackage{inter},字体显示恢复正常,但我希望使用lualatex作为texsystem。我已更新字体文件,且在LaTeX文件中字体显示正常。
原因分析与修复方案
原因
- Fedora系统默认未将用户自定义字体目录
~/.fonts纳入字体缓存,导致LuaLaTeX通过fontspec无法正确定位Inter字体 - 固定的
Scale=0.88参数与Matplotlib自身的字体缩放逻辑冲突,引发渲染异常 - 仅设置
pgf.rcfonts = False可能未完全让LuaLaTeX接管所有文本元素的渲染,存在混合渲染问题
修复方案
1. 刷新系统字体缓存
在终端执行以下命令,强制Fedora识别~/.fonts目录下的字体:
fc-cache -fv ~/.fonts
执行完成后重启Python环境,让Matplotlib能通过fontspec正常调用Inter字体。
2. 调整PGF预配置参数
修改pgf.preamble的字体调用方式,解决路径识别和缩放冲突问题:
plt.rcParams.update({ 'font.family': 'sans-serif', 'font.size': 12, 'pgf.texsystem': 'lualatex', 'pgf.preamble': r'\usepackage{unicode-math,fontspec}\setmathfont{STIX Two Math}\setsansfont[Path=~/.fonts/, Scale=MatchLowercase]{Inter}', 'pgf.rcfonts' : False, 'text.usetex': True # 强制所有文本由LaTeX渲染 })
Path=~/.fonts/:直接指定字体文件路径,绕开系统缓存识别问题Scale=MatchLowercase:让无衬线字体的小写字母大小与数学字体匹配,替代固定缩放值避免冲突text.usetex=True:强制Matplotlib将所有文本交给LuaLaTeX处理,消除混合渲染异常
3. 验证字体可用性
若问题仍存在,先单独验证LuaLaTeX能否正常调用Inter字体:
创建测试LaTeX文件test.tex:
\documentclass{standalone} \usepackage{fontspec} \setsansfont{Inter}[Scale=MatchLowercase] \begin{document} Cubic Function Input data ($x$) Output data ($f(x)$) \end{document}
用LuaLaTeX编译:
lualatex test.tex
若编译后的PDF字体显示正常,说明问题仅出在Matplotlib与LuaLaTeX的交互配置上,可重新检查Python代码中的rcParams设置。
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

