在matplotlib中使用latex实现无衬线数学字体

25 投票
3 回答
24440 浏览
提问于 2025-04-15 20:59

下面这个脚本:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl

mpl.rc('font', family='sans-serif')
mpl.rc('text', usetex=True)

fig = mpl.figure()
ax = fig.add_subplot(1,1,1)
ax.text(0.2,0.5,r"Math font: $451^\circ$")
ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\circ$")

fig.savefig('test.png')

是想在matplotlib中用LaTeX来使用无衬线字体。但是问题是,数学字体还是衬线字体(从坐标轴上的数字和中间的标签可以看出来)。有没有办法把数学字体也设置成无衬线字体呢?

3 个回答

2

这段话的意思是,如果你像我一样更喜欢使用Computer Modern Sans字体而不是Helvetica字体,那么你可以通过下面的代码来实现。

mpl.rcParams['text.usetex'] = True 
mpl.rcParams['text.latex.preamble'] = [r'\usepackage[cm]{sfmath}']
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'cm'
15

最简单的方法是使用matplotlib自带的TeX功能,比如:

import pylab as plt
params = {'text.usetex': False, 'mathtext.fontset': 'stixsans'}
plt.rcParams.update(params)

如果你想用外部的LaTeX,可以选择CM Bright字体,比如:

params = {'text.usetex': True, 
          'text.latex.preamble': [r'\usepackage{cmbright}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)

需要注意的是,CM Bright字体是不可缩放的,所以你不能保存成PDF或PS格式!我发现其他使用外部LaTeX的选项也是这样。

32

我在我的matplotlibrc文件里总是设置text.usetex = True。除此之外,我还会使用这个:

mpl.rcParams['text.latex.preamble'] = [
       r'\usepackage{siunitx}',   # i need upright \micro symbols, but you need...
       r'\sisetup{detect-all}',   # ...this to force siunitx to actually use your fonts
       r'\usepackage{helvet}',    # set the normal font here
       r'\usepackage{sansmath}',  # load up the sansmath so that math -> helvet
       r'\sansmath'               # <- tricky! -- gotta actually tell tex to use!
]  

希望这能帮到你。

撰写回答