legend顯示圖例
1 legend基礎
函數原型legend(*args, **kwargs)
當len(args) == 2
args是[artist]和[label]的集合
當len(args) == 0
args會自動調用get_legend_handles_labels()生成
等價于
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
ax.get_legend_handles_labels()的作用在于返回ax.lines, ax.patch所有對象以及ax.collection中的LineCollectionorRegularPolyCollection對象
注意:這里只提供有限支持,并不是所有的artist都可以被用作圖例,比如errorbar支持不完善
1.1調整順序
ax=subplot(1,1,1)
p1,=ax.plot([1,2,3], label="line1")
p2,=ax.plot([3,2,1], label="line2")
p3,=ax.plot([2,3,1], label="line3")
handles, labels=ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
importoperatorhl=sorted(zip(handles,labels), key=operator.itemgetter(1))
handles2, labels2=zip(*hl)
ax.legend(handles2, labels2)
1.2使用代理artist
當需要使用legend不支持的artist時,可以使用另一個被legend支持的artist作為代理
比如以下示例中使用不在axe上的一個artist
p=Rectangle((0,0), 1, 1,fc="r")
legend([p], ["RedRectangle"])
2多列圖例
ax1=plt.subplot(3,1,1)
ax1.plot([1], label="multinline")
ax1.plot([1], label="$2^{2^2}$")
ax1.plot([1], label=r"$frac{1}{2}pi$")
ax1.legend(loc=1, ncol=3, shadow=True)
ax2=plt.subplot(3,1,2)
myplot(ax2)
ax2.legend(loc="center left", bbox_to_anchor=[0.5,0.5],
ncol=2, shadow=True, title="Legend")
ax2.get_legend().get_title().set_color("red")
3圖例位置
ax.legend(…., loc=3)具體對應位置如下圖
繪制在圖上是這樣的,(具體沒有分清5和7的區別)
4多個圖例
如果不采取措施,連續調用兩個legend會使得后面的legend覆蓋前面的
frommatplotlib.pyplotimport*p1,=plot([1,2,3], label="test1")
p2,=plot([3,2,1], label="test2")
l1=legend([p1], ["Label1"],loc=1)l2=legend([p2], ["Label2"],loc=4)# this removes l1 from the axes.
gca().add_artist(l1)# add l1 as a separate artist to the axes
5. API
class matplotlib.legend.Legend(parent,handles, labels,**args)
三個最重要的必要參數
parent --- legend的父artist, 包含legend的對象
比如用ax.legend()調用之后
>>> print ax.get_legend().parent
Axes(0.125,0.1;0.775x0.8)
handles ---圖例上面畫出的各個artist(lines, patches)
labels --- artist對應的標簽
其他參數
Keyword
Description
loc
a location code
prop
the font property (matplotlib.font_manager.FontProperties對象)
eg
song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8)
fontsize
the font size (和prop互斥,不可同時使用)
markerscale
the relative size of legend markers vs. original
numpoints
the number of points in the legend for line
scatterpoints
the number of points in the legend for scatter plot
scatteryoffsets
a list of yoffsets for scatter symbols in legend
frameon
if True, draw a frame around the legend. If None, use rc
fancybox
if True, draw a frame with a round fancybox. If None, use rc
shadow
if True, draw a shadow behind legend
ncol
number of columns
borderpad
the fractional whitespace inside the legend border
labelspacing
the vertical space between the legend entries
handlelength
the length of the legend handles
handleheight
the length of the legend handles
handletextpad
the pad between the legend handle and text
borderaxespad
the pad between the axes and legend border
columnspacing
the spacing between columns
title
the legend title
bbox_to_anchor
the bbox that the legend will be anchored.
bbox_transform
the transform for the bbox. transAxes if None.
主要函數
get_frame() ---返回legend所在的方形對象
get_lines()
get_patches()
get_texts()
get_title() ---上面幾個比較簡單,不解釋了
set_bbox_to_anchor(bbox, transform=None)
(…本函數待續…之后寫axes的時候會加入,目前我沒有看懂他的這個長寬和figure以及axes的關系)
6.樣例
leg=ax.legend(('Model length','Data length','Total message length'),
'upper center', shadow=True)
# the matplotlib.patches.Rectangle instance surrounding the legend即外框
frame=leg.get_frame()
frame.set_facecolor('0.80')# set the frame face color to light gray
# matplotlib.text.Text instances即legend中文本
fortinleg.get_texts():
t.set_fontsize('small')# the legend text fontsize
# matplotlib.lines.Line2D instances即legend中所表示的artist
forlinleg.get_lines():
l.set_linewidth(1.5)# the legend line width
fig=plt.figure()
ax1=fig.add_axes([0.1,0.1,0.4,0.7])
ax2=fig.add_axes([0.55,0.1,0.4,0.7])
x=np.arange(0.0,2.0,0.02)
y1=np.sin(2*np.pi*x)
y2=np.exp(-x)
l1, l2=ax1.plot(x, y1,'rs-', x, y2,'go')
y3=np.sin(4*np.pi*x)
y4=np.exp(-2*x)
l3, l4=ax2.plot(x, y3,'yd-', x, y3,'k^')
fig.legend((l1, l2), ('Line 1','Line 2'),'upper left')
fig.legend((l3, l4), ('Line 3','Line 4'),'upper right')
原文參考:http://blog.sina.com.cn/s/blog_b09d460201019c10.html