Forgot password?
 Create new account
View 131|Reply 1

matplotlib 中 LaTeX 的数学文本

[Copy link]

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

hbghlyj Posted at 2024-10-19 05:30:49 |Read mode
使用 LaTeX 进行文本渲染
Matplotlib 可以使用 LaTeX 来渲染文本。这可以通过在您的 rcParams 中设置 text.usetex : True 来激活,或者通过将 usetex 属性设置为 True 来激活单个 Text 对象。通过 LaTeX 处理文本比 Matplotlib 非常强大的 mathtext 速度更慢,但更灵活,因为可以使用不同的 LaTeX 包(字体包、数学包等)。结果可能很惊人,尤其是在您注意在图形中使用与主文档相同的字体时。
Matplotlib 的 LaTeX 支持需要一个可用的 LaTeX 安装。对于 *Agg 后端,还需要 dvipng;对于 PS 后端,还需要 PSfragdvipsGhostscript。对于 PDF 和 SVG 后端,如果存在 LuaTeX,它将用于加速一些后处理步骤,但请注意,它不用于解析 TeX 字符串本身(只支持 LaTeX)。这些外部依赖项的可执行文件必须全部位于您的 PATH 中。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib import rc
  4. rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
  5. rc('text', usetex=True)
  6. #rc('text.latex', preamble=r'\usepackage[eulergreek]{sansmath}\sansmath')
  7. t = np.arange(0.0, 2.0, 0.01)
  8. s = np.sin(2*np.pi*t)
  9. figure()
  10. plt.plot(t,s)
  11. plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
  12. plt.text(1, -0.6, r'$\displaystyle\sum_{i=0}^\infty x_i$', fontsize=20)
  13. plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
  14.          fontsize=20)
  15. plt.xlabel('time (s)')
  16. plt.ylabel('volts (mV)')
  17. plt.savefig('fig_latex.pdf')
Copy the Code

xwN1z[1].png

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

 Author| hbghlyj Posted at 2024-10-19 05:34:25
hbghlyj 发表于 2024-10-18 21:30
通过 LaTeX 处理文本比 mathtext 速度更慢,但更灵活
以下是比较:
mathtext versionLaTeX version
ePZKh[1].png xwN1z[3].png

手机版Mobile version|Leisure Math Forum

2025-4-20 22:02 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list