1、添加圖例
>>> import matplotlib.pyplot as plt >>> import numpy as np >>> x = np.linspace(-3, 3, 50) >>> y1 = 2*x + 1 >>> y2 = x**2 >>> plt.figure() <Figure size 640x480 with 0 Axes> >>> plt.xlim((-1, 2)) (-1, 2) >>> plt.ylim((-2, 3)) (-2, 3) >>> new_sticks = np.linspace(-1, 2, 5) >>> plt.xticks(new_sticks) ([<matplotlib.axis.XTick object at 0x000001C38FA6F198>, <matplotlib.axis.XTick object at 0x000001C38F57F748>, <matplotlib.axis.XTick object at 0x000001C38F57F0F0>, <matplotlib.axis.XTick object at 0x000001C38F516D30>, <matplotlib.axis.XTick object at 0x000001C38F59D908>], <a list of 5 Text xticklabel objects>) >>> plt.yticks([-2, -1.8, -1, 1.22, 3], ... [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) ([<matplotlib.axis.YTick object at 0x000001C38F50E668>, <matplotlib.axis.YTick object at 0x000001C38F2DD828>, <matplotlib.axis.YTick object at 0x000001C38F57FBE0>, <matplotlib.axis.YTick object at 0x000001C38F59D6A0>, <matplotlib.axis.YTick object at 0x000001C38F59D438>], <a list of 5 Text yticklabel objects>) >>> l1, = plt.plot(x, y1, label='linear line') >>> l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line') #legend將要顯示的信息來自於上面代碼中的 label. 所以我們只需要簡單寫下一下代碼, plt 就能自動的為我們添加圖例 #參數 loc='upper right' 表示圖例將添加在圖中的右上角. >>> plt.legend(loc='upper right') <matplotlib.legend.Legend object at 0x000001C38B7D8780> >>> plt.show()
2、調整位置和名稱
如果我們想單獨修改之前的 label
信息, 給不同類型的線條設置圖例信息. 我們可以在 plt.legend
輸入更多參數. 如果以下面這種形式添加 legend, 我們需要確保, 在上面的代碼 plt.plot(x, y2, label='linear line')
和 plt.plot(x, y1, label='square line')
中有用變量 l1
和 l2
分別存儲起來. 而且需要注意的是 l1,
l2,
要以逗號結尾, 因為plt.plot()
返回的是一個列表.
>>> plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best') <matplotlib.legend.Legend object at 0x000001C38FA44630> >>> plt.show()
其中’loc’參數有多種,’best’表示自動分配最佳位置,其余的如下:
'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,