莫烦老师Matplotlib学习笔记(一)
2020-06-28 13:44:29 来源:易采站长站 作者:易采站长站整理

1.4 legend图例
plt.legend()
画出label的标注
可以设置位置等信息,
具体见代码
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really bad$', r'$bad$', r'$mormal$', r'$good$', r'$really good$'])
l1, = plt.plot(x, y2, label='up')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down')
plt.legend(handles=[l1, l2], labels=['aaa', 'bbb'], loc='lower right')
plt.show()

1.5 Annotation标注
在图片上标注一些文字或者箭头说明
plt.text()
在图片上加一些纯文字说明
plt.annotate()
在图片上加一些箭头符号等文字说明
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-3, 3, 50)
y = 2 * x + 1
plt.figure(num=1, figsize=(8, 5), )
plt.plot(x, y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
'''画点'''
x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')
'''画垂直虚线'''
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)
'''画箭头和文字说明'''
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
plt.text(-3.7, 3, r'$This is the text$', fontdict={'size': 16, 'color': 'r'})
plt.show()

1.6 tick能见度
刻度有可能被遮挡
ax.get_xticklabels()
得到各个坐标轴的刻度
刻度可以设置各个性质
同事要注意图层顺序zorder的大小设置
zorder越大,则越在上面
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-3, 3, 50)
y = 0.1 * x
plt.figure()
plt.plot(x, y, linewidth=10,zorder=1)













闽公网安备 35020302000061号