matplotlib可以为可见对象(Artist,比如线条、形状)添加图例(legend)。官方建议使用pyplot模块的legend函数简便的创建图例,而不是使用底层的matplotlib.legend类构造图例。

函数签名为matplotlib.pyplot.legend(*args, **kwargs)

legend()基本应用演示

使用图例的基础有两个:

  • handles:可见对象(Artist,比如线条、形状)序列,与labels配合使用。
  • labels:类型为字符串列表,即图例中显示的文本集合。

两者的长度最好一致,否则按照长度最小的进行截断。

调用方式有三种:

  • legend():根据可见对象和标签自动构造图例。
  • legend(labels):自动匹配可见对象和labels官方不建议使用这种方式,因为可见对象和标签的对应关系并不明确!
  • legend(handles, labels):指定可见对象和标签的对应关系。

案例

演示legend函数的三种调用方式。

import matplotlib.pyplot as plt

plt.figure(figsize=(13,4))
plt.subplot(131)
# legend()调用方式
plt.plot([1, 1],label='1')
plt.plot([2, 2],label='2')
plt.legend()
plt.subplot(132)
# legend(labels)调用方式
plt.plot([1, 1])
plt.plot([2, 2])
plt.legend(['1','2'])
plt.subplot(133)
# legend(handles, labels)调用方式
# 注意plot函数返回的为Line2D对象列表
line1, = plt.plot([1, 1])
line2, = plt.plot([2, 2])
print(type(line1))
plt.legend((line1,line2),['1st','2nd'])
plt.show()

在这里插入图片描述

legend()其他参数

  • loc:图例显示的位置,类型为浮点数或字符串,默认值为rcParams["legend.loc"] ( 'best')。浮点数和字符串之间具有以下对应关系:
    位置字符串位置编码
    ‘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
  • ncol:图例显示的列数。类型为整数,默认值为1
  • prop:字体属性。Nonematplotlib.font_manager.FontProperties或字典。默认为None,使用rcParmas中字体相关设置。
  • fontsize:标签字体大小。整数或{'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}。只有设置了prop参数,fontsize属性才生效。
  • labelcolor:标签颜色。字符串或字符串列表,可以为颜色格式或'linecolor''markerfacecolor' ('mfc')'markeredgecolor' ( 'mec')
  • numpoints:图例中标记点的个数。类型为整数,默认值为rcParams["legend.numpoints"] (1)。适用于折线图Line2D对象。
  • scatterpoints:图例中标记点的个数。类型为整数,默认值为rcParams["legend.scatterpoints"] (1)。适用于散点图。
  • markerfirst:图表标记是否在左侧。类型为布尔值,默认值为True
  • markerscale:图例标记的缩放比例。类型为浮点数,默认值为rcParams["legend.markerscale"] (1.0)
  • frameon:图例区域是否有边框。类型为布尔值。默认值为:rcParams["legend.frameon"] (True)
  • fancybox:图例区域矩形是否为圆角。类型为布尔值。默认值为:rcParams["legend.fancybox"] ( True)
  • shadow:图例区域是否有阴影。类型为布尔值。默认值为:rcParams["legend.shadow"] ( False)
  • title:图例标题。类型为字符串或None,默认值为None,即没有图例标题。
  • title_fontsize:标题字体大小。整数或{'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}。默认值为rcParams["legend.title_fontsize"] (None)
  • facecolor:图例区域背景色。"inherit"或 色彩值,默认值为rcParams["legend.facecolor"] ('inherit')。如果使用"inherit",使用rcParams["axes.facecolor"] ( 'white')
  • edgecolor:图例区域边缘颜色。"inherit"或 色彩值,默认值为rcParams["legend.edgecolor"] ('0.8')。如果使用"inherit",使用rcParams["axes.edgecolor"] ('black')
  • borderpad:图例边框填充距离。浮点值,单位为字体大小单位。默认值为rcParams["legend.borderpad"] (0.4)
  • labelspacing:图例条目之间的垂直距离。浮点值,单位为字体大小单位。默认值为rcParams["legend.labelspacing"] ( 0.5)
  • handlelength:图例标记的长度。浮点值,单位为字体大小单位。默认值为rcParams["legend.handlelength"] (2.0)
  • handletextpad:图例标记和标签的距离。浮点值,单位为字体大小单位。默认值为rcParams["legend.handletextpad"] ( 0.8)
  • borderaxespad:图例与子图边缘之间的填充距离。浮点值,单位为字体大小单位。默认值为rcParams["legend.borderaxespad"] (0.5)
  • columnspacing:图例列间距。浮点值,单位为字体大小单位。默认值为 rcParams["legend.columnspacing"] (2.0)

图例相关rcParams参数:

#legend.loc:           best
#legend.frameon:       True     # if True, draw the legend on a background patch
#legend.framealpha:    0.8      # legend patch transparency
#legend.facecolor:     inherit  # inherit from axes.facecolor; or color spec
#legend.edgecolor:     0.8      # background patch boundary color
#legend.fancybox:      True     # if True, use a rounded box for the
                                # legend background, else a rectangle
#legend.shadow:        False    # if True, give background a shadow effect
#legend.numpoints:     1        # the number of marker points in the legend line
#legend.scatterpoints: 1        # number of scatter points
#legend.markerscale:   1.0      # the relative size of legend markers vs. original
#legend.fontsize:      medium
#legend.title_fontsize: None    # None sets to the same as the default axes.

## Dimensions as fraction of fontsize:
#legend.borderpad:     0.4  # border whitespace
#legend.labelspacing:  0.5  # the vertical space between the legend entries
#legend.handlelength:  2.0  # the length of the legend lines
#legend.handleheight:  0.7  # the height of the legend handle
#legend.handletextpad: 0.8  # the space between the legend line and legend text
#legend.borderaxespad: 0.5  # the border between the axes and legend edge
#legend.columnspacing: 2.0  # column separation

案例:图例外观设置

对比自定义图例外观与默认图例外观。
左图设置了以下图例外观:标题为’legends’(默认为空),图例显示为2列(默认为1列),标签显示在左边(默认为左侧),图例标记点显示为2个(默认为1个),图例区域矩形为直角(默认为圆角),图例背景色为灰色,图例边缘为红色,图例显示阴影(默认无)。

import matplotlib.pyplot as plt

line1, = plt.plot([1, 1], marker='o')
line2, = plt.plot([2, 2])
plt.legend((line1, line2), ['1st', '2nd'], loc=0,
           title='legends', ncol=2, markerfirst=False,
           numpoints=2, frameon=True, fancybox=True,
           facecolor='gray', edgecolor='r', shadow=True)
plt.show()

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐