如何在 matplotlib 中将 rc 参数 `usetex=True` 与其他字体一起使用

Paa*_*lon 2 python matplotlib python-3.x

我想用乳胶和其他字体进行绘图,但似乎只有乳胶字体可用。如何使用 usetex 启用其他字体?

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('font', family='Arial')

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

绘制的图像

Max*_*Noe 5

使用usetex=True

您必须为 matplotlib 使用自己的 LaTeX 标头。然后,您可以使用字体包来选择字体。

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True
plt.rcParams['text.latex.preamble'] = r'''
\usepackage{mathtools}

\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
% more packages here
'''

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Run Code Online (Sandbox Code Playgroud)

结果: 使用结果

使用 pgf 后端

通过使用 pgf 后端,您可以获得最大的灵活性。这需要在系统中安装最新的 LaTeX。

对我来说,最实用的方法是使用 amatplotlibrc和 a header-matplotlib.tex,并将 texfile 包含在 matplotlibrc 中。但是,由于 matplotlib 在 tmp 目录中运行 tex,因此您需要将当前目录添加到TEXINPUTS.

例子:

matplotlibrc

backend: pgf  # use the pgf backend
pgf.rcfonts : False # setup the fonts yourself in the header
text.usetex : True 
text.latex.unicode : True
pgf.texsystem : lualatex
pgf.preamble : \input{header-matplotlib.tex}
Run Code Online (Sandbox Code Playgroud)

header-matplotlib.tex

\usepackage{fontspec}
\setsansfont{Arial}  # for the example I used Fira Sans

\usepackage{amssymb}
\usepackage{mathtools}

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}

% more packages here
Run Code Online (Sandbox Code Playgroud)

pgf_plot.py(这个变得小得多,因为我们在 `matplotlibrc 中设置选项)

import matplotlib.pyplot as plt
import numpy as np

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Run Code Online (Sandbox Code Playgroud)

运行使用

$ TEXINPUTS=$(pwd): python pgf_plots.py
Run Code Online (Sandbox Code Playgroud)

结果:

结果

这种方法可以扩展,以使绘图的字体和字体大小与文档中使用的字体和字体大小相匹配,请参阅此处的示例: https: //github.com/Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE/tree/master/examples/use_system_latex

  • 使用 Matplotlib 3.0,我收到“MatplotlibDeprecationWarning:”:*“text.latex.unicode” rcparam 在 Matplotlib 2.2 中已弃用,并将在 3.1 中删除。*。寻找替代品让我看到了这篇文章,因此更新它以获取新的 Matplotlib 版本可能会很有用。 (4认同)