Matplotlib 对 LaTeX 的支持

时间:2022-04-11 06:40:06

Matplotlib 对 LaTeX 提供了很好的支持。只需要将 LaTeX 表达式封装在 美元符号 内,就可以在图的任何文本中显示了,比如 “$y=x^3$”

在 LaTeX 中常常会用到反斜杠,比如 \alpha 来产生符号 $\alpha$ 。但反斜杠在 Python 字符串中是有特殊含义的, 为了不出错需要使用原始文本,只需要在字符串的前面加个r就行了,像是 r”\alpha” 或者 r’\alpha’:

# Update the matplotlib configuration parameters:

#from matplotlib import rcParams
#rcParams.update({'font.size': 18, 'font.family': 'serif'}) / rcParams.update({'font.size': 18, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})
#若需要更改全局字体大小或者类型则加上上两行,STIX 字体是一种好选择

#rcParams.update({'font.size': 18, 'text.usetex': True})
#也可以将图中的文本全用 Latex 渲染

# 重置
#matplotlib.rcParams.update({'font.size': 12, 'font.family': 'sans', 'text.usetex': False})

fig, ax = plt.subplots()

ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.legend(loc=2) # upper left corner
ax.set_xlabel(r'$\alpha$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('title');

fig
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Matplotlib 对 LaTeX 的支持


http://blog.****.net/baidu_38060633/article/details/69511731