LaTeX 不适用于 matplotlib 文本

LaTeX not working on matplotlib text

每当我想为绘图标签和文本渲染 LaTeX 时,我就一直遇到这个问题,它有时对某些符号有效,但对其他符号无效。例如,在此处显示的我的脚本中生成以下图:

from matplotlib import rc
plt.rc('text', usetex=True)
plt.plot(a_t,asol[:,0],label ='$\psi$')
plt.plot(a_t,rho,label ="$\rho/\rho_c$")
plt.xlabel(r"$\xi$",fontsize=15)
from matplotlib.legend_handler import HandlerLine2D
plt.legend(loc='upper left',prop={'size':12},numpoints=1)

我试过其他符号,$\pi$ 工作正常但 $\theta$ 只显示 "heta" 而没有 t。我很困惑为什么有些符号适用于 LaTeX 而有些则不行。

谢谢!

请记住,Python 字符串中的某些字符具有特殊含义,例如\r 表示回车 return,\t 表示制表符。这就是为什么您有时只会得到奇怪的结果,因为 \p 没有特殊含义。因此,要么通过转义确保您的反斜杠被视为文字反斜杠:

plt.plot(a_t,rho,label = "$\rho/\rho_c$")

或使用原始字符串:

plt.plot(a_t,rho,label = r"$\rho/\rho_c$")