matplotlib繪製圖例

本文摘自“莫煩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()

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章