Python matplotlib畫圖時圖例說明(legend)放到圖像外側詳解
用python的matplotlib畫圖時,往往需要加圖例說明。如果不設置任何參數,默認是加到圖像的內側的最佳位置。
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) plt.legend() plt.show()
這樣的結果如圖所示:

如果需要將該legend移到圖像外側,有多種方法,這里介紹一種。
在plt.legend()函數中加入若干參數:
plt.legend(bbox_to_anchor=(num1, num2), loc=num3, borderaxespad=num4)
bbox_to_anchor(num1,num2)表示legend的位置和圖像的位置關系,num1表示水平位置,num2表示垂直位置。num1=0表示legend位于圖像的左側垂直線(這里的其它參數設置:num2=0,num3=3,num4=0)。

num1=1表示legend位于圖像的右側垂直線(其它參數設置:num2=0,num3=3,num4=0)。

為了美觀,需要將legend放于圖像的外側,而又距離不是太大,一般設num1=1.05。
num2=0表示legend位于圖像下側水平線(其它參數設置:num1=1.05,num3=3,num4=0)。

num2=1表示legend位于圖像上側水平線(其它參數設置:num1=1.05,num3=3,num4=0)。

所以,如果希望legend位于圖像的右下,需要將num2設為0,位于圖像的右上,需要將num2設為1。
由于legend是一個方框,bbox_to_anchor=(num1, num2)相當于表示一個點,那么legend的哪個位置位于這個點上呢。參數num3就用以表示哪個位置位于該點。
| 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 |
所以,當設bbox_to_anchor=(1.05,0),即legend放于圖像右下角時,為美觀起見,需要將legend的左下角,即'lower left'放置該點,對應該表的‘Location Code'數字為3,即參數num3置為3或直接設為‘lower left';而當設bbox_to_anchor=(1.05,1),即legend放于圖像右上角時,為美觀起見,需要將legend的左上角,即'upper left'放置該點,對應該表的‘Location Code'數字為2,即參數num3置為2或直接設為‘upper left'。
根據參考網址上的解釋,參數num4表示軸和legend之間的填充,以字體大小距離測量,默認值為None,但實際操作中,如果不加該參數,效果是有一定的填充,下面有例圖展示,我這里設為0,即取消填充,具體看個人選擇。
這是將legend放于圖像右下的完整代碼:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) plt.legend(bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0) plt.show()
效果展示:

這里legend的‘lower left'置于(1.05, 0)的位置。
如果不加入參數num4,那么效果為:

legend稍靠上,有一定的填充。
這是將legend放于圖像右上的完整代碼:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0) plt.show()
效果展示:

這里legend的‘upper left'置于(1.05, 0)的位置。
如果不加入參數num4,那么效果為:

legend稍靠下。
以上這篇Python matplotlib畫圖時圖例說明(legend)放到圖像外側詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python手拉手教你爬取貝殼房源數據的實戰(zhàn)教程
隨著人工智能的不斷發(fā)展,機器學習這門技術也越來越重要,很多人都開啟了學習機器學習,本文就介紹了機器學習的基礎內容,了解python爬蟲,本文給大家分享Python爬取貝殼房源數據的實戰(zhàn)教程,感興趣的朋友一起學習吧2021-05-05
老生常談Python startswith()函數與endswith函數
下面小編就為大家?guī)硪黄仙U凱ython startswith()函數與endswith函數。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
在Python的Django框架下使用django-tagging的教程
這篇文章主要介紹了在Python的Django框架下使用django-tagging的教程,針對網絡編程中的tag部分功能提供幫助,需要的朋友可以參考下2015-05-05

