Sans-serif数学与matplotlib中的乳胶

ast*_*rog 21 python latex matplotlib

以下脚本:

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')
Run Code Online (Sandbox Code Playgroud)

尝试在matplotlib中使用带有LaTeX的sans-serif字体.问题是数学字体仍然是衬线字体(由轴编号表示,并由中心的标签所示).有没有办法将数学字体设置为sans-serif?

Pau*_*l H 26

我总是text.usetex = True在我的matplotlibrc文件中.除此之外,我也使用它:

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!
]  
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


小智 13

最简单的方法是使用matplotlib的内部TeX,例如:

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

如果您使用外部LaTeX,您可以使用例如CM Bright字体:

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

请注意,CM Bright字体不可扩展,您将无法保存PDF/PS!与迄今为止我发现的外部LaTeX的其他选项相同.