在圖中插入 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')

StackOverflow 文件 程式碼可以生成以下圖表

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