matplotlib绘图调用Minion Pro字体报错及不生效问题咨询
核心原因
- 初始代码填写的
MinionPro-Regular是字体的子样式名称,font.family参数需要填写字体家族名Minion Pro,因此会触发字体找不到的报错。 - 开启
usetex=True后,matplotlib的全局字体配置对LaTeX渲染的文本、数学公式不生效,LaTeX有独立的字体调用规则,这就是修改为Minion Pro后不报错但最终渲染字体不对的核心原因。
解决方案
方案1:保留usetex模式(需要本地已安装LaTeX发行版)
需要在LaTeX预处理逻辑中指定使用Minion Pro字体,修改配置部分代码如下:
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # 配置非LaTeX渲染部分的字体 mpl.rcParams['font.family'] = 'Minion Pro' mpl.rcParams['font.serif'] = ['Minion Pro'] + mpl.rcParams['font.serif'] # 开启usetex并配置LaTeX字体 mpl.rc('text', usetex=True) # 如果你的LaTeX发行版已安装minionpro包,用下面的preamble mpl.rc('text.latex', preamble=r''' \usepackage{bm} \usepackage{minionpro} ''') # 如果没有安装minionpro包,改用fontspec调用系统字体,需取消注释下面的配置,同时将编译器改为xelatex/lualatex # mpl.rc('text.latex', preamble=r''' # \usepackage{bm} # \usepackage{fontspec} # \setmainfont{Minion Pro} # ''') # mpl.rcParams['text.latex.compiler'] = 'xelatex' # 后续绘图代码保持不变 x = np.arange(0,2*np.pi,0.1) y = np.sin(x) fig, ax = plt.subplots() ax.plot(x,y, label ='Exact') ax.set_xlabel(r"$\bm{x}$", fontsize=20) ax.xaxis.label.set_color('red') ax.set_ylabel(r"$\bm{y}$", fontsize=20) ax.yaxis.label.set_color('red') ax.set_title("My title", size=20) plt.legend() plt.show()
方案2:关闭usetex,使用matplotlib内置mathtext渲染(无需安装LaTeX,更简单)
直接通过matplotlib的mathtext配置指定公式字体,无需依赖LaTeX环境:
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # 全局字体配置 mpl.rcParams['font.family'] = 'Minion Pro' # 数学公式字体配置 mpl.rcParams['mathtext.fontset'] = 'custom' mpl.rcParams['mathtext.rm'] = 'Minion Pro' mpl.rcParams['mathtext.it'] = 'Minion Pro:italic' mpl.rcParams['mathtext.bf'] = 'Minion Pro:bold' # 后续绘图代码保持不变 x = np.arange(0,2*np.pi,0.1) y = np.sin(x) fig, ax = plt.subplots() ax.plot(x,y, label ='Exact') ax.set_xlabel(r"$\bm{x}$", fontsize=20) ax.xaxis.label.set_color('red') ax.set_ylabel(r"$\bm{y}$", fontsize=20) ax.yaxis.label.set_color('red') ax.set_title("My title", size=20) plt.legend() plt.show()
字体识别异常排查
如果配置后仍然提示找不到Minion Pro,按以下步骤排查:
- 安装字体时需右键点击字体文件,选择「为所有用户安装」,仅当前用户安装的字体matplotlib默认无法扫描到。
- 运行以下代码确认matplotlib是否识别到该字体:
from matplotlib.font_manager import fontManager fonts = [f.name for f in fontManager.ttflist] print([f for f in fonts if 'Minion' in f])
- 如果输出为空,删除matplotlib字体缓存:运行
print(mpl.get_cachedir())获取缓存目录,删除目录下的fontlist-xxx.json文件,重启Python后重新运行即可重新扫描系统字体。
内容的提问来源于stack exchange,提问作者user1393214
相关产品推荐
相关产品推荐

