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

Matplotlib中usetex=True时如何修改LaTeX字体?

解决Matplotlib开启usetex=True时无法使用本地数学字体的问题

当usetex=True时,Matplotlib会调用系统LaTeX引擎渲染所有文本(包括数学公式),完全绕过自身的mathtext模块,所以你之前设置的mathtext.*系列参数、甚至fontdict都不会生效——这些配置只在usetex关闭时起作用。要在usetex模式下替换数学字体,需要从LaTeX引擎的配置入手:

关键步骤

  1. 确保LaTeX能识别Neo Euler字体

    • 优先使用XeLaTeX或LuaLaTeX(原生支持OpenType字体),需先在系统中安装Neo Euler字体,或准备好字体文件的绝对路径。
    • 若用pdfLaTeX,需将Neo Euler转换为LaTeX支持的Type1字体,操作繁琐,不推荐。
  2. 配置Matplotlib调用XeLaTeX引擎并加载字体
    通过修改rcParams指定TeX引擎,并添加LaTeX预声明代码来加载目标字体。

  3. 修改后的完整代码

from matplotlib import pyplot as plt
import matplotlib

# 移除冗余元素的配置保持不变
matplotlib.rcParams['axes.spines.bottom'] = False
matplotlib.rcParams['axes.spines.left']   = False
matplotlib.rcParams['axes.spines.right']  = False
matplotlib.rcParams['axes.spines.top']    = False
matplotlib.rcParams['xtick.major.size']    = 0
matplotlib.rcParams['xtick.labelsize']    = 0
matplotlib.rcParams['ytick.major.size']    = 0
matplotlib.rcParams['ytick.labelsize']    = 0

testString = r'Thrust Coefficient \\ $\displaystyle \mathbf{C_T}$'

# 核心配置:指定XeLaTeX引擎+LaTeX预加载字体
matplotlib.rcParams.update({
    "text.usetex": True,
    "font.size": 36,
    # LaTeX预声明:用fontspec加载Neo Euler作为主字体和数学字体
    "text.latex.preamble": r'\usepackage{fontspec}\setmainfont{Neo Euler}\setmathfont{Neo Euler}',
    # 指定TeX引擎为XeLaTeX
    "pgf.texsystem": "xelatex",
})

fig, (ax1, ax2, ax3) = plt.subplots(3,1)
ax1.text(0.5,0.5, testString, ha='center')

# 此时无需额外修改字体参数,所有文本由LaTeX统一处理
ax2.text(0.5,0.5, testString, ha='center')
ax3.text(0.5,0.5, testString, ha='center')

fig.tight_layout()
plt.show()

额外注意事项

  • 如果Neo Euler不在系统默认字体路径,可在\setmainfont和\setmathfont中指定字体文件绝对路径,示例:
    \setmainfont[Path=/your/font/path/]{NeoEuler-Regular.otf}
    \setmathfont[Path=/your/font/path/]{NeoEuler-Regular.otf}
    
  • 确保你的LaTeX环境(如TeX Live、MikTeX)已安装fontspec包,XeLaTeX/LuaLaTeX的默认发行版通常自带该包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:35:27