Python matplotlib畫圖時(shí)圖例說明(legend)放到圖像外側(cè)詳解
用python的matplotlib畫圖時(shí),往往需要加圖例說明。如果不設(shè)置任何參數(shù),默認(rèn)是加到圖像的內(nèi)側(cè)的最佳位置。
import matplotlib.pyplot as pltimport 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()
這樣的結(jié)果如圖所示:
如果需要將該legend移到圖像外側(cè),有多種方法,這里介紹一種。
在plt.legend()函數(shù)中加入若干參數(shù):
plt.legend(bbox_to_anchor=(num1, num2), loc=num3, borderaxespad=num4)
bbox_to_anchor(num1,num2)表示legend的位置和圖像的位置關(guān)系,num1表示水平位置,num2表示垂直位置。num1=0表示legend位于圖像的左側(cè)垂直線(這里的其它參數(shù)設(shè)置:num2=0,num3=3,num4=0)。
num1=1表示legend位于圖像的右側(cè)垂直線(其它參數(shù)設(shè)置:num2=0,num3=3,num4=0)。
為了美觀,需要將legend放于圖像的外側(cè),而又距離不是太大,一般設(shè)num1=1.05。
num2=0表示legend位于圖像下側(cè)水平線(其它參數(shù)設(shè)置:num1=1.05,num3=3,num4=0)。
num2=1表示legend位于圖像上側(cè)水平線(其它參數(shù)設(shè)置:num1=1.05,num3=3,num4=0)。
所以,如果希望legend位于圖像的右下,需要將num2設(shè)為0,位于圖像的右上,需要將num2設(shè)為1。
由于legend是一個(gè)方框,bbox_to_anchor=(num1, num2)相當(dāng)于表示一個(gè)點(diǎn),那么legend的哪個(gè)位置位于這個(gè)點(diǎn)上呢。參數(shù)num3就用以表示哪個(gè)位置位于該點(diǎn)。
loc參數(shù)對(duì)應(yīng) 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所以,當(dāng)設(shè)bbox_to_anchor=(1.05,0),即legend放于圖像右下角時(shí),為美觀起見,需要將legend的左下角,即’lower left’放置該點(diǎn),對(duì)應(yīng)該表的‘Location Code’數(shù)字為3,即參數(shù)num3置為3或直接設(shè)為‘lower left’;而當(dāng)設(shè)bbox_to_anchor=(1.05,1),即legend放于圖像右上角時(shí),為美觀起見,需要將legend的左上角,即’upper left’放置該點(diǎn),對(duì)應(yīng)該表的‘Location Code’數(shù)字為2,即參數(shù)num3置為2或直接設(shè)為‘upper left’。
根據(jù)參考網(wǎng)址上的解釋,參數(shù)num4表示軸和legend之間的填充,以字體大小距離測量,默認(rèn)值為None,但實(shí)際操作中,如果不加該參數(shù),效果是有一定的填充,下面有例圖展示,我這里設(shè)為0,即取消填充,具體看個(gè)人選擇。
這是將legend放于圖像右下的完整代碼:
import matplotlib.pyplot as pltimport 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)的位置。
如果不加入?yún)?shù)num4,那么效果為:
legend稍靠上,有一定的填充。
這是將legend放于圖像右上的完整代碼:
import matplotlib.pyplot as pltimport 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)的位置。
如果不加入?yún)?shù)num4,那么效果為:
legend稍靠下。
以上這篇Python matplotlib畫圖時(shí)圖例說明(legend)放到圖像外側(cè)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC使用異步Action的方法2. 詳解瀏覽器的緩存機(jī)制3. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解4. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容5. XML解析錯(cuò)誤:未組織好 的解決辦法6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?8. 使用css實(shí)現(xiàn)全兼容tooltip提示框9. XML入門的常見問題(二)10. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐
