[matplotlib] Legend 图例

发布时间 2023-06-24 20:24:17作者: Jet_P

组成

  1. legend entries
    图例项,每个项包括一个key和一个label
  2. legend key
  3. legend label
  4. legend handler
    即产生legend entry的相应的原对象。

创建legend

ax.legend(handlers, labels)

handlers和labels可以是列表,labels可以利用handler对象自己的label,也可以设置legend的时候重新设置。

handlers可以是axes上现有的对象,也可以是单独创建对象作为handler,例如:

fig, ax = plt.subplots()
red_patch = mpatches.Patch(color='red', label='The red data')
ax.legend(handles=[red_patch])

legend定位

  1. 通过legend()中的loc参数设置
  2. 通过legend()中的bbox_to_anchor参数设置
    这个参数设置的自由度很高。可以是一个2-tuple,此时两个数字分别为(x,y),即legend图框所在的坐标。也可以是一个4-tuple,此时4个数字分别为(x, y, width, height)。
    box的坐标可以是figure上的坐标,此时可以设置axes外的legend,默认是axes上的坐标。
    要调整坐标参照系,可以设置bbox_transform参数,默认是axes.transAxes,可以调整为fig.transFigure。

Figure上的legend

可以直接在figure上创建legend,使用函数fig.legend(),使用方法同ax.legend()。
figure上多次使用legend()方法可以创建多个legend。

Axes上创建多个legend

Axes上重复使用legend()方法只会生成一个legend,正确的方法如下:

fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4)

# Create a legend for the first line.
first_legend = ax.legend(handles=[line1], loc='upper right')

# Add the legend manually to the Axes.
ax.add_artist(first_legend)

# Create another legend for the second line.
ax.legend(handles=[line2], loc='lower right')

一些技巧

举例说明几种技巧:

  1. 通过调整handlermap来调整图例key的样式
from matplotlib.legend_handler import HandlerLine2D

fig, ax = plt.subplots()
line1, = ax.plot([3, 2, 1], marker='o', label='Line 1')
line2, = ax.plot([1, 2, 3], marker='o', label='Line 2')

# 下面代码使图例上显示4个点
ax.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
  1. 两个图例的key重叠成一个key
from numpy.random import randn

z = randn(10)

fig, ax = plt.subplots()
red_dot, = ax.plot(z, "ro", markersize=15)
# Put a white cross over some of the data.
white_cross, = ax.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
# 下面代码将red_dot和white_cross的图例合在一起变成红圈中含白十字
ax.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
  1. 两个图例的key放在一个entry,只有1个label
from matplotlib.legend_handler import HandlerLine2D, HandlerTuple

fig, ax = plt.subplots()
p1, = ax.plot([1, 2.5, 3], 'r-d')
p2, = ax.plot([3, 2, 1], 'k-o')

l = ax.legend([(p1, p2)], ['Two keys'], numpoints=1,
              handler_map={tuple: HandlerTuple(ndivide=None)})