1、打印特殊符号
matplotlib在公式书写上面跟latex很相似,接下来我们就特殊符号,上标下标来具体展示一下。
import matplotlib.pyplot as plt
x = [i+1 for i in range(20)]
y = x
plt.figure()
plt.title(r'$\alpha$ > $\beta$') # 打印α>β
plt.xlabel(r'$\theta$') # 打印θ
plt.ylabel(r'$\omega$') # 打印ω
plt.plot(x, y)
plt.show()
效果如下:
由此可见,打印特殊符号需要知道特殊符号的英文名称,在前面加上转义符反斜杠,再用一对美元符号包起来即可。
接下来,我们尝试打印下标和上标。下标需要加"_",上标需要加"^",这跟latex语法完全一样。
import matplotlib.pyplot as plt
x = [i+1 for i in range(20)]
y = x
plt.figure()
plt.title(r'$\alpha_i$ > $\beta_i$') # 打印α_i > β_i
plt.xlabel(r'$\theta^2$') # 打印θ^2
plt.ylabel(r'$\omega^n$') # 打印ω^n
plt.plot(x, y)
plt.show()
我们看看效果:
更多符号对应字母请见下图:
2、制作图例,legend函数
import matplotlib.pyplot as plt
from math import sin, cos, exp
x = [(i+1)/100 for i in range(1000)]
y1 = [sin(i) for i in x]
y2 = [cos(i) for i in x]
y3 = [exp(-i) for i in x]
plt.figure()
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
# 分别对应y1,y2,y3标志图例,注意e^(-x)要加大括号表示(-x)是一个整体,都是上标
plt.legend(['sin(x)', 'cos(x)', '$e^{-x}$'])
plt.show()
在文章最后附上参考链接~
https://matplotlib.org/users/mathtext.html