在matplotlib中使用latex,Linux系统

在使用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,会报错。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值