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

如何统一Word公式与Matplotlib绘图的数学字体(STIX Two/Cambria Math)

问题解答

字体差异原因

Matplotlib中plt.rcParams['mathtext.fontset'] = 'stix'对应的是STIX Version 1字体,而Word里的「STIX Two Math」是STIX字体的Version 2版本,二者属于不同的字体迭代版本,在字形细节、字符比例、符号设计上均有区别,因此显示效果不一致。

解决建议

要让Matplotlib数学字体与Word公式字体完全一致,需要针对目标字体(STIX Two Math或Cambria Math)配置Matplotlib的mathtext参数,而非仅修改普通文本字体。以下是具体操作:

方法1:使用STIX Two Math

  1. 找到Windows系统中STIX Two Math字体的OTF文件路径,通常为C:\Windows\Fonts\STIXTwoMath-Regular.otf(若路径不同请自行调整)
  2. 通过代码配置mathtext使用该字体:
from matplotlib import rcParams
import matplotlib.font_manager as fm

# 加载STIX Two Math字体
stix_two_path = r"C:\Windows\Fonts\STIXTwoMath-Regular.otf"
stix_two_font = fm.FontProperties(fname=stix_two_path)

# 配置mathtext和普通文本统一使用该字体
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.rm'] = stix_two_font.get_name()
rcParams['mathtext.it'] = stix_two_font.get_name()
rcParams['mathtext.bf'] = stix_two_font.get_name()
rcParams['font.family'] = stix_two_font.get_name()

方法2:使用Cambria Math

  1. 找到Cambria Math字体路径,Windows下通常为C:\Windows\Fonts\CambriaMath.ttf
  2. 代码配置如下:
from matplotlib import rcParams
import matplotlib.font_manager as fm

# 加载Cambria Math字体
cambria_path = r"C:\Windows\Fonts\CambriaMath.ttf"
cambria_font = fm.FontProperties(fname=cambria_path)

# 配置mathtext和普通文本统一使用该字体
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.rm'] = cambria_font.get_name()
rcParams['mathtext.it'] = cambria_font.get_name()
rcParams['mathtext.bf'] = cambria_font.get_name()
rcParams['font.family'] = cambria_font.get_name()

关键说明

之前仅指向OTF文件的方法只对普通文本生效,是因为Matplotlib的数学文本($...$包裹内容)由mathtext独立模块控制,必须将mathtext.fontset设为custom,并为mathtext.rm/it/bf等参数指定目标字体,才能让数学公式应用该字体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:30:32