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

如何在Matplotlib中为LaTeX公式及所有文本设置Arial字体

如何在Matplotlib中为LaTeX公式和普通文本统一设置Arial字体?

当你启用usetex=True时,Matplotlib会把所有文本(包括LaTeX公式)的渲染工作交给系统的LaTeX引擎处理,这时候你之前配置的mathtext.rm这类参数就会被完全忽略——这就是Arial字体没应用到公式上的核心原因。要解决这个问题,得从LaTeX本身的字体配置入手,下面给你两种可行的解决方案:

方案1:基于pdfLaTeX的配置(适配多数默认TexLive环境)

这个方案依赖helvet和sansmath两个LaTeX包:前者会将无衬线字体替换为Arial(实际映射为Helvetica,多数系统会自动关联到Arial),后者让数学公式也使用无衬线字体,确保和Arial的文本风格统一。

修改后的完整代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# 配置LaTeX预命令,全局启用Arial风格字体
mpl.rcParams['text.latex.preamble'] = r'''
\usepackage{helvet}
\usepackage{sansmath}
\sansmath
'''
mpl.rc('font', family='sans-serif')  # 全局指定使用无衬线字体
mpl.rc('text', usetex=True)
mpl.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(10, 10))
x, y = np.arange(10), np.arange(10)
plt.scatter(x, y, s=100, color="r")
plt.xlabel(r"TEST: $\phi\times\eta$", fontsize=25, labelpad=10)
plt.ylabel(r"TEST: $\varepsilon\times\zeta$", fontsize=25, labelpad=10)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.text(x=1, y=6, s=r"TEST: $x\times y$", fontsize=30)
plt.show()

方案2:基于XeLaTeX的配置(精准指定Arial字体)

如果你想确保完全使用系统中的Arial字体而非Helvetica替代,可以用XeLaTeX配合fontspec包直接加载系统字体,需要先指定Matplotlib使用XeLaTeX编译器:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# 指定使用XeLaTeX编译器,支持fontspec加载系统本地字体
mpl.rcParams['pgf.texsystem'] = 'xelatex'
# 配置LaTeX预命令,直接将Arial设为全局字体
mpl.rcParams['text.latex.preamble'] = r'''
\usepackage{fontspec}
\setmainfont{Arial}
\setsansfont{Arial}
\usepackage{sansmath}
\sansmath
'''
mpl.rc('font', family='Arial')
mpl.rc('text', usetex=True)
mpl.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(10, 10))
x, y = np.arange(10), np.arange(10)
plt.scatter(x, y, s=100, color="r")
plt.xlabel(r"TEST: $\phi\times\eta$", fontsize=25, labelpad=10)
plt.ylabel(r"TEST: $\varepsilon\times\zeta$", fontsize=25, labelpad=10)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.text(x=1, y=6, s=r"TEST: $x\times y$", fontsize=30)
plt.show()

关键注意点

  • 两种方案中的sansmath包和\sansmath命令是核心:它们让LaTeX的数学符号也使用无衬线字体,保证公式和Arial文本的风格统一。
  • 如果你的TexLive环境中没有helvet或sansmath包,可以用包管理器安装:tlmgr install helvet sansmath。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:22:49