在使用matplotlib进行画图时,经常需要输入一些数学表达式。
对于一般的表达式,matplotlib内置的mathtext已经可以满足我们的需求了。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label=r'$\sqrt{x^2}$')
ax.legend()
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} '
r'\Delta_{i+1}^j$', fontsize=20)
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
fig.tight_layout()
fig.savefig("test.png")
# Ref: https://matplotlib.org/stable/gallery/text_labels_and_annotations/mathtext_demo.html
上面画的图可以满足我们的需求,但有时候,可能我们需要输入的表达式并不能被mathtext很好地显示出来,而Latex通常可以满足我们的需求。那如何在matplotlib中使用Latex呢,以下是我尝试后得到的有效方案,我是在WSL(windows subsystem linux)上尝试的。
下面的代码可以输出更加漂亮的表达式,代码中只需要加入reParams的配置部分,参考这里
import matplotlib.pyplot as plt
plt.rcParams.update({
"text.usetex": True,
"font.family": "Helvetica"
})
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label=r'$\sqrt{x^2}$')
ax.legend()
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
ax.set_title(r'$\Delta_i^j \hspace{0.4cm} \mathrm{versus} \hspace{0.4cm} '
r'\Delta_{i+1}^j$', fontsize=20)
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
fig.tight_layout()
fig.savefig("test_latex.png")
但是如果直接在Linux中运行上面的代码,如果没有安装Latex,会报错无法运行。
那么如何安装Latex?在Linux中输入sudo apt-get install -y texlive texlive-latex-extra texlive-latex-recommended dvipng cm-super msttcorefonts
就可以了,参考这里。
错误的安装方式:在cmd中输入latex,如果还没有安装latex则会让你通过sudo apt install texlive-latex-base安装,在cmd中输入这个命令安装。这样安装后,在matplotlib中还是没法用latex,会报错。