Matplotlib 中使用 Latex 公式
Suraj Joshi
2024年2月15日
Matplotlib
Matplotlib LaTex
本教程解释了我们如何在 Matplotlib 中显示 LaTex 公式或方程。
在 Matplotlib Python 中编写 LaTex 公式
import math
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * math.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel(r"$\sin (x)$")
plt.title("Plot of sinx")
plt.show()
输出:

它将在 Matplotlib 图中显示 LaTex 公式。
要在 Matplotlib 中渲染 LaTex 公式,我们必须将'text.usetex'设置为 True。我们可以使用下面的脚本来检查'text.usetex'的值。
import matplotlib
print(matplotlib.rcParams["text.usetex"])
输出:
False
如果你的系统将'text.usetex'改为 True,你可能会得到 True 的输出。如果'text.usetex'被设置为 False,我们可以使用下面的脚本将'text.usetex'设置为 True。
import matplotlib
matplotlib.rcParams["text.usetex"] = True
我们还需要有 LaTex、dvipng 和 Ghostscript (9.0 或更新版本)来渲染 LaTex 公式,并将所有的安装依赖关系添加到 PATH 中。
我们也可以在 Matplotlib 中使用 Tex 格式渲染希腊字母和更多的符号。
import numpy as np
import matplotlib.pyplot as plt
alpha = x = np.linspace(0, 10, 10)
y1 = alpha
y2 = alpha ** 2
y3 = alpha ** 3
plt.plot(x, y1, label=r"$\alpha$")
plt.plot(x, y2, label=r"$\alpha^2$")
plt.plot(x, y3, label=r"$\alpha^3$")
plt.xlabel(r"$\alpha$")
plt.legend()
plt.show()
输出:

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn