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中的LineCollectionor RegularPolyCollection对象
注意:这里只提供有限支持, 并不是所有的artist都可以被用作图例,比如errorbar支持不完善
1.1 调整顺序
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")
handles, labels = ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
import operator hl = 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], ["Red Rectangle"])
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覆盖前面的
from matplotlib.pyplot import * p1, = plot([1,2,3], label="test1")
p2, = plot([3,2,1], label="test2")
l1 = legend([p1], ["Label 1"], loc=1) l2 = legend([p2], ["Label 2"], 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中文本
for t in leg.get_texts():
t.set_fontsize('small') # the legend text fontsize
# matplotlib.lines.Line2D instances 即legend中所表示的artist
for l in leg.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')