1. 程式人生 > >matplotlib之legend

matplotlib之legend

man tab 檢測 ould mba float plot left 關系

  在《matplotlib極坐標系應用之雷達圖》 中,我們提出了這個問題“圖例中每種成員的顏色是怎樣和極坐標相應的成員的顏色相對應的呢”,那麽接下來我們說說legend的一般使用和設置。

調用legend()一般有三種方式:

方式1. 自動檢測,直接調用legend();
  在plot()時就指定圖例labels,再直接調用legend()就好了,或者在plot中指定plot elements,然後通過set_label函數指定圖例labels

1 plt.plot([1, 2, 3], label=Inline label)
2 plt.legend()
3 
4 line, = plt.plot([1, 2, 3])#此處的逗號非常重要,如果沒有的話line是一個list對象;加上的話line是一個matplotlib.lines.Line2D對象,才能調用set_label()函數
5 line.set_label(Label via method) 6 plt.legend()

技術分享圖片技術分享圖片

方式2. 顯示指定labels,調用legend(labels);
  但是,這種方式會使plot elements 和 labels的對應關系不明顯,所以並不建議使用這種方式。

  Note: This way of using is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.

1 plt.plot([1, 2, 3])
2 plt.plot([1, 4, 9])
3 plt.legend([A simple line,2 simple line])

  技術分享圖片

方式3. 顯示指定plot elements 和 labels,調用legend(handles, labels)
  handles : sequence of Artist/lines/patches
    A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
    The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
  labels : sequence of strings, optional
    A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

  

1 line1, = plt.plot([1,2,3])
2 print(type(line1))
3 line2, = plt.plot([1,4,9])
4 line3, = plt.plot([1,8,27])
5 handles = (line1, line2, line3)
6 labels = (label1, label2, label3)
7 plt.legend(handles, labels)

技術分享圖片

legend()的返回值:class:`matplotlib.legend.Legend` instance

其他參數說明:

loc : int or string or pair of floats, default: ‘upper right’

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

  ncol : integer(設置圖例顯示列數)
    The number of columns that the legend has. Default is 1.

  prop : None or matplotlib.font_manager.FontProperties or dict(設置圖例字體)
    The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

references:

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html?highlight=legend#matplotlib.pyplot.legend

https://matplotlib.org/tutorials/intermediate/legend_guide.html#sphx-glr-tutorials-intermediate-legend-guide-py

matplotlib之legend