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

如何在Matplotlib中结合usetex=True参数使用其他字体?

在Matplotlib启用usetex时使用非LaTeX字体的解决方案

当你开启usetex=True后,Matplotlib会把所有文本的渲染工作交给LaTeX处理,这时候直接设置font.family='Arial'是不会生效的——因为LaTeX会完全接管字体的选择逻辑。下面是两种实用的解决思路,帮你实现普通文本用自定义字体、数学公式用LaTeX字体的需求:

方法一:通过LaTeX预配置指定字体

既然文本由LaTeX渲染,那我们可以直接在LaTeX的预导言(preamble)里加载字体包,指定普通文本的字体,同时保留LaTeX默认的数学字体。

针对传统PDFLaTeX环境

如果你的系统用的是默认的PDFLaTeX,可以用helvet包加载Helvetica字体(和Arial视觉几乎一致),然后把默认字体族切换为无衬线字体:

import numpy as np
import matplotlib.pyplot as plt

# 开启usetex,并配置LaTeX预导言
plt.rc('text', usetex=True)
# 加载helvet包,设置默认字体为无衬线(Helvetica)
plt.rc('text.latex', preamble=r'\usepackage{helvet} \renewcommand{\familydefault}{\sfdefault}')

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

这样设置后,普通文本会用Helvetica,数学公式还是LaTeX默认的Computer Modern字体,风格统一。

针对XeLaTeX/LuaLaTeX环境

如果想使用真正的Arial字体,可以借助fontspec包,同时指定Matplotlib用XeLaTeX渲染:

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
# 指定用XeLaTeX渲染
plt.rc('pgf', texsystem='xelatex')
# 在预导言中加载fontspec并设置Arial为主字体
plt.rc('text.latex', preamble=r'\usepackage{fontspec} \setmainfont{Arial}')

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

注意:这种方法需要你的系统已经安装Arial字体,并且LaTeX环境支持XeLaTeX。

方法二:混合模式——仅数学公式用LaTeX风格字体

如果你不想完全依赖LaTeX渲染所有文本,可以关闭全局usetex,只让数学公式使用LaTeX风格的字体,普通文本由Matplotlib直接控制:

import numpy as np
import matplotlib.pyplot as plt

# 关闭全局usetex
plt.rc('text', usetex=False)
# 设置普通文本用Arial
plt.rc('font', family='Arial')
# 设置数学公式用和LaTeX一致的Computer Modern字体
plt.rc('mathtext', fontset='cm')

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

这种方式更灵活,不需要调整LaTeX环境,而且普通文本的字体设置和常规Matplotlib用法完全一致,数学公式的视觉效果也和LaTeX输出一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:41:05