python 无衬线数学与 matplotlib 中的乳胶

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2537868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:52:46  来源:igfitidea点击:

Sans-serif math with latex in matplotlib

pythonlatexmatplotlib

提问by astrofrog

The following script:

以下脚本:

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: 1^\circ$")
ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\circ$")

fig.savefig('test.png')

is an attempt to use a sans-serif font in matplotlib with LaTeX. The issue is that the math font is still a serif font (as indicated by the axis numbers, and as demonstrated by the labels in the center). Is there a way to set the math font to also be sans-serif?

是尝试在 matplotlib 和 LaTeX 中使用无衬线字体。问题是数学字体仍然是衬线字体(如轴号所示,以及中心标签所示)。有没有办法将数学字体设置为无衬线字体?

回答by Paul H

I always have text.usetex = Truein my matplotlibrc file. In addition to that, I use this as well:

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!
]  

Hope that helps.

希望有帮助。

回答by Vyacheslav

The easiest way is to use matplotlib's internal TeX, e.g.:

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

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

If you use an external LaTeX, you can use, e.g., CM Bright fonts:

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

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

Note, that the CM Bright font is non-scalable, and you'll not be able to save PDF/PS! Same with other options with external LaTeX I've found so far.

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

回答by nedim

This will enable you to use the Computer Modern Sans font if you, as I, prefer it over Helvetica:

如果你像我一样喜欢它而不是 Helvetica,这将使你能够使用 Computer Modern Sans 字体:

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'