处理文本(数学表达式)¶

在字符串中使用一对 $$ 符号可以利用 Tex 语法打出数学表达式,而且并不需要预先安装 Tex。在使用时我们通常加上 r 标记表示它是一个原始字符串(raw string)

In [1]:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. %matplotlib inline

In [2]:

  1. # plain text
  2. plt.title('alpha > beta')
  3.  
  4. plt.show()

06.04 处理文本(数学表达式) - 图1

In [3]:

  1. # math text
  2. plt.title(r'$\alpha > \beta$')
  3.  
  4. plt.show()

06.04 处理文本(数学表达式) - 图2

上下标¶

使用 _^ 表示上下标:

$\alpha_i > \beta_i$:

  1. r'$\alpha_i > \beta_i$'

$\sum\limits_{i=0}^\infty x_i$:

  1. r'$\sum_{i=0}^\infty x_i$'

注:

  • 希腊字母和特殊符号可以用 '\ + 对应的名字' 来显示
  • {} 中的内容属于一个部分;要打出花括号是需要使用 {}

分数,二项式系数,stacked numbers¶

$\frac{3}{4}, \binom{3}{4}, \stackrel{3}{4}$:

  1. r'$\frac{3}{4}, \binom{3}{4}, \stackrel{3}{4}$'

$\frac{5 - \frac{1}{x}}{4}$:

  1. r'$\frac{5 - \frac{1}{x}}{4}$'

在 Tex 语言中,括号始终是默认的大小,如果要使括号大小与括号内部的大小对应,可以使用 \left\right 选项:

$(\frac{5 - \frac{1}{x}}{4})$

  1. r'$(\frac{5 - \frac{1}{x}}{4})$'

$\left(\frac{5 - \frac{1}{x}}{4}\right)$:

  1. r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'

根号¶

$\sqrt{2}$:

  1. r'$\sqrt{2}$'

$\sqrt[3]{x}$:

  1. r'$\sqrt[3]{x}$'

特殊字体¶

默认显示的字体是斜体,不过可以使用以下方法显示不同的字体:

命令 显示
\mathrm{Roman} $\mathrm{Roman}$
\mathit{Italic} $\mathit{Italic}$
\mathtt{Typewriter} $\mathtt{Typewriter}$
\mathcal{CALLIGRAPHY} $\mathcal{CALLIGRAPHY}$
\mathbb{blackboard} $\mathbb{blackboard}$
\mathfrak{Fraktur} $\mathfrak{Fraktur}$
\mathsf{sansserif} $\mathsf{sansserif}$

$s(t) = \mathcal{A}\ \sin(2 \omega t)$:

  1. s(t) = \mathcal{A}\ \sin(2 \omega t)

注:

  • Tex 语法默认忽略空格,要打出空格使用 '\ '
  • \sin 默认显示为 Roman 字体

音调¶

命令 结果
\acute a $\acute a$
\bar a $\bar a$
\breve a $\breve a$
\ddot a $\ddot a$
\dot a $\dot a$
\grave a $\grave a$
\hat a $\hat a$
\tilde a $\tilde a$
\4vec a $\vec a$
\overline{abc} $\overline{abc}$
\widehat{xyz} $\widehat{xyz}$
\widetilde{xyz} $\widetilde{xyz}$

特殊字符表¶

参见:http://matplotlib.org/users/mathtext.html#symbols

例子¶

In [4]:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. t = np.arange(0.0, 2.0, 0.01)
  4. s = np.sin(2*np.pi*t)
  5.  
  6. plt.plot(t,s)
  7. plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
  8. plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
  9. plt.text(0.6, 0.6, r'$\mathcal{A}\ \mathrm{sin}(2 \omega t)$',
  10. fontsize=20)
  11. plt.xlabel('time (s)')
  12. plt.ylabel('volts (mV)')
  13. plt.show()

06.04 处理文本(数学表达式) - 图3

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/06-matplotlib/06.04-working-with-text---math-expression.ipynb