matplotlib的学习5-legend图例

import matplotlib.pyplot as plt
import numpy as np

'''
legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构.
'''

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
#set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really bad$', r'$bad$', r'$normal$', r'$good$', r'$really good$'])

# set line syles
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')#lable 就是显示的名字

# legend将要显示的信息来自于上面代码中的 label. 所以我们只需要简单写下一下代码, plt 就能自动的为我们添加图例.
plt.legend(loc='upper right')#所谓的图例就是标识出来线段的lable  legend means 图例

# 如果想单独修改之前的label信息,给不同类型的线条设置图例的信息,我们可以在legend输入更多的参数
# 如果以下面的这种形式添加legend,我们需要担保,在上面的代码中用了l1和l2分别把他们存储了起来,
# 注意这里l1,l2要用逗号来结尾,因为plt.plot()返回的是一个列表

plt.legend(handles=[l1,l2],labels=['up','down'],loc='best')

plt.show()

#其中loc的参数有很多,'best'表示自动分配最佳的位置

 l1 = plt.plot(x,y1,lable='linear line')  表示l1是一条线,x,y参数确定,lable表示这个线在figure里面的名称

plt.legend(loc='upper right') #plt的图例放置的位置在loc参数中

plt.legend(handles=[l1,l2],lables=['up','down'],loc='best')在此代码中把l1,l2的图例调下位置,loc的参数有很多best表示的是自动调整到最佳的位置

原文地址:https://www.cnblogs.com/simon-idea/p/9580542.html