matplotLib Legend添加图例:展示数据的信息
用法:
legend(): 默认获取各组数据的Label并展示在图框左上角
legend(labels):
legend(handles, labels,loc)
画出两组线性图:y1 = x2+1; y2 =x*2,先定义x轴和y 轴的相关属性
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 50) # x的取值从-1到2,元素个数50
y1 = x*2 + 1
y2 = x**2
plt.figure() # 定义窗口
plt.xlim(-1, 2) # x轴的取值范围,-1到2
plt.xticks(np.linspace(-1, 2, 5)) # x轴的刻度,从-1到2,有5个刻度
plt.ylim(-2, 3) # y轴的取值范围从-2到3
# y轴的刻度,以及各个刻度的名称
plt.yticks([-2, -1.8, -1, 1.22, 3], [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
- 画两组线型图,使用legend(),注意两组线段必须有label,否则不会显示图例
# 画出x与y1的线性图, 标签名称是linear line, 线段默认颜色是蓝色, 注意plt.plot() 返回的是列表,需要在l1和l2之后加逗号。
l1, = plt.plot(x, y1, label='linear line')
# 画出x与y2的线性图,线段颜色是红色,线段宽度是2.0, 线段类型是虚线,标签名称是square line
l2, = plt.plot(x, y2, color='red', linewidth=2.0, linestyle='--', label='square line')
plt.legend()
plt.show()
- plt.legend(labels):可在lablels中重新定义线段的标签
plt.legend(('line1', 'line2'))
- legend(handles, label, loc): handles是指要处理的数据线段,labels指线段的标签,loc设置图例的位置
plt.legend(handles=[l1, l2], labels=['line1', 'line2'], loc='upper right')
下面是loc的值:
loc: 位置(取值类型:int or string or pair of floats) 'best' for axes, 'upper right' for figures
Location String Location Code
'best' 0 ---> 表示分配最佳位置
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
具体用法可以参考官方文档:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html