在图中插入 TeX 公式
可以使用 rc
函数将 TeX 公式插入图中
import matplotlib.pyplot as plt
plt.rc(usetex = True)
或访问 rcParams
:
import matplotlib.pyplot as plt
params = {'tex.usetex': True}
plt.rcParams.update(params)
TeX 使用反斜杠\
作为命令和符号,这可能与 Python 字符串中的特殊字符冲突。为了在 Python 字符串中使用文字反斜杠,必须将它们转义或合并到原始字符串中:
plt.xlabel('\\alpha')
plt.xlabel(r'\alpha')
代码可以生成以下图表
import matplotlib.pyplot as plt
plt.rc(usetex = True)
x = range(0,10)
y = [t**2 for t in x]
z = [t**2+1 for t in x]
plt.plot(x, y, label = r'$\beta=\alpha^2$')
plt.plot(x, z, label = r'$\beta=\alpha^2+1$')
plt.xlabel(r'$\alpha$')
plt.ylabel(r'$\beta$')
plt.legend(loc=0)
plt.show()
不支持显示的公式(例如 $$...$$
或\begin{equation}...\end{equation}
)。然而,使用\displaystyle
可以显示数学风格。
要加载乳胶包,请使用 tex.latex.preamble
参数:
params = {'text.latex.preamble' : [r'\usepackage{siunitx}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)
但是,请注意示例 matplotlibrc 文件中的警告 :
#text.latex.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
# AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
# IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
# preamble is a comma separated list of LaTeX statements
# that are included in the LaTeX document preamble.
# An example:
# text.latex.preamble : \usepackage{bm},\usepackage{euler}
# The following packages are always loaded with usetex, so
# beware of package collisions: color, geometry, graphicx,
# type1cm, textcomp. Adobe Postscript (PSSNFS) font packages
# may also be loaded, depending on your font settings