python - matplotlib 中的 Latex 脚本

标签 python matplotlib latex legend axis-labels

我希望使用 latex 脚本 $\theta$ 来标记 matplotlib 图中的轴和图例。所以我使用下面的代码。

y = np.linspace(0, 2*np.pi, 200)
plt.plot(y, np.sin(y)*np.cos(y), lw=3, label='$sin(\theta) cos(\theta)$')

plt.xlabel('$\theta$', fontsize=40)
plt.ylabel('$P(\theta,t)$', fontsize=40)

但是这不起作用并返回下图 enter image description here

该代码适用于 $\Theta$,但我不想更改变量名称。 $\rho$、$\tau$、$\alpha$、$\beta$ 也会出现同样的问题。请提供一些有关如何摆脱此问题的提示。

感谢您的帮助。

最佳答案

使用原始字符串,否则字符串中的 \t 将被解释为 TAB

Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.

您通常应该对包含 Latex 表达式的字符串执行此操作,因为它们通常包含反斜杠。

y = np.linspace(0, 2*np.pi, 200)
plt.plot(y, np.sin(y)*np.cos(y), lw=3, label=r'$sin(\theta) cos(\theta)$')

plt.xlabel(r'$\theta$', fontsize=40)
plt.ylabel(r'$P(\theta,t)$', fontsize=40)

enter image description here

关于python - matplotlib 中的 Latex 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45073493/

相关文章:

python - 如何将参数传递给 animation.FuncAnimation()?

linux - 为什么 org-preview-latex-fragment 在 OSX 中的工作速度比在 Linux 中慢 10 倍?

latex - Latex 文档中的奇怪 Bibtex 行为

latex - 如何在章节标题下添加作者副标题?

python - Python中的相对路径

python - 从命令提示符运行 python 脚本时没有模块错误

python - 有没有办法在没有箭袋的情况下绘制箭袋键或在 matplotlib 中隐藏箭袋?

python - 如何重新缩放 matplotlib 直方图中的计数

python - Pytorch BCELoss 对相同输入使用不同的输出

python - pyqt - 将图像复制到 QClipboard 崩溃程序