一、問題提出
我有這樣一串代碼:
import matplotlib.pyplot as plt
plt.figure(figsize = (10, 6))
"
此處省略代碼
"
legend.append("J")
plt.legend(legend)
plt.xlabel('recall')
plt.ylabel('precision')
plt.grid()
plt.show()
我們得到的圖像為:
二、嘗試美化
2.1 改變legend的位置
plt.legend(loc='lower right', fontsize=12, frameon=True, fancybox=True, framealpha=0.2, borderpad=0.3,
ncol=1, markerfirst=True, markerscale=1, numpoints=1, handlelength=3.5)
loc
:圖例位置,可取(‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center , right’, ‘lower center’, ‘upper center’, ‘center’) ;若是使用了bbox_to_anchor,則這項(xiàng)就無效了;
fontsize
:int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},字體大??;
frameon
:是否顯示圖例邊框;
ncol
: 圖例的列的數(shù)量,默認(rèn)為1;
title
: 為圖例添加標(biāo)題;
shadow
: 是否為圖例邊框添加陰影;
markerfirst
: True表示圖例標(biāo)簽在句柄右側(cè),false反之;
markerscale
: 圖例標(biāo)記為原圖標(biāo)記中的多少倍大??;
numpoints
: 表示圖例中的句柄上的標(biāo)記點(diǎn)的個(gè)數(shù),一般設(shè)為1;
fancybox
: 是否將圖例框的邊角設(shè)為圓形;
framealpha
: 控制圖例框的透明度;
borderpad
: 圖例框內(nèi)邊距;
labelspacing
: 圖例中條目之間的距離;
handlelength
: 圖例句柄的長度;
bbox_to_anchor
: (橫向看右,縱向看下),如果要自定義圖例位置或者將圖例畫在坐標(biāo)外邊,用它,比如bbox_to_anchor=(1.4, 0.8),這個(gè)一般配合著ax.get_position(),set_position([box.x0, box.y0, box.width*0.8 , box.height])使用;
用不到的參數(shù)可以直接去掉,有的參數(shù)沒寫進(jìn)去,用得到的話加進(jìn)去 , bbox_to_anchor=(1.11, 0)
例如,我這里只改loc參數(shù):
plt.legend(legend, loc = 'lower right')
2.2 matplotlib設(shè)置圖片邊緣距離
import matplotlib.pyplot as plt
plt.figure(figsize = (10, 6))
plt.subplots_adjust(left = 0.1, right = 0.7, top = 0.9, bottom = 0.1)
legend = []
我們得到的結(jié)果如下圖所示:
可以很明顯的看到,右邊有很大的空白出來!
2.3 plt.lengend圖例放在圖像的外側(cè)
num1 = 1.121
num2 = 1.0
num3 = 0
num4 = 0.1
plt.legend(legend, bbox_to_anchor = (num1, num2), loc = num3, borderaxespad = num4)
plt.xlabel('recall')
plt.ylabel('precision')
plt.grid()
plt.show()
最后大家再繼續(xù)微調(diào)即可!
說明:bbox_to_anchor
被賦予的二元組中,num1用于控制legend的左右移動,值越大越向右邊移動,num2用于控制legend的上下移動,值越大,越向上移動。用于微調(diào)圖例的位置。文章來源:http://www.zghlxwxcb.cn/news/detail-602433.html
num1表示水平位置,num2表示垂直位置。文章來源地址http://www.zghlxwxcb.cn/news/detail-602433.html
到了這里,關(guān)于【Python】matplotlib設(shè)置圖片邊緣距離和plt.lengend圖例放在圖像的外側(cè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!