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)
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 后端,您可以获得最大的灵活性。这需要在系统中安装最新的 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
| 归档时间: |
|
| 查看次数: |
4160 次 |
| 最近记录: |