本文摘自“莫烦Python”,感兴趣者可自行查看!
绘制曲线
本文以两条曲线为例,为其绘制图例。
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
plt.figure()
plt.xlim((-1,2))#设置x座标轴范围
plt.ylim((-2,3))
new_sticks=np.linspace(-1,2,5) #修改x座标轴刻度
plt.xticks(new_sticks)
plt.yticks([-2,-1.8,-1,1.22,3],['really bad','bad','normal','good','really ',
'good'])
legend绘制图例的第一种形式,后续不能修改曲线图例类型
plt.plot(x,y1,label='linear line') #设置曲线的类型
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='square line')
plt.legend(loc='upper right')#绘制曲线图例,信息来自类型label
lengend绘制图例的第二种形式,后续可以修改图例中曲线类型
l1,=plt.plot(x,y1,label='linear line') #plt.plot()返回的是一个列表
l2,=plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='square line')
#loc参数:best,upper right,upper left,lower left,lower right,right,center left,
# center right,lower center,upper center,center(亦可0,1,2,3,4,5,6,7,8,9,10)
plt.legend(handles=[l1,l2],labels=['up','down'],loc='best') #best表示自动分配最佳位置
plt.show()