Matplotlib 系列之「Legend 图例」

Matplotlib 的 Legend 图例就是为了帮助我们展示每个数据对应的图像名称,更好的让读者认识到你的数据结构。

如图,红色标注部分就是 Legend 图例。

在之前的一篇文章 Matplotlib 系列之「绘制函数图像」 中已经细讲过 Matplotlib 的绘制过程以及结构分析,希望读者能先去了解一下。

接着上一次的代码继续讲解 Legend 图例如何展示,以及有哪些常用的特性。

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2

plt.figure(num=3,figsize=(8,5))
l1=plt.plot(x,y2)
l2=plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')

plt.legend(handles=[l1,l2],labels=['up','down'],loc='best')

plt.xlabel('x')
plt.ylabel('y')

plt.xlim((-1,2))
plt.ylim((-2,3))

new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
          [r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])

ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))

plt.show()
复制代码

上一节中仔细绘制了 Matplotlib 的图像结构,现在可以进行回顾一下。

Title 为图像标题,Axis 为坐标轴, Label 为坐标轴标注,Tick 为刻度线,Tick Label 为刻度注释,Legend 为图例。

设置 Legend 图例

这里我们将 Legend 图例设置成 如上图中所示,即 up 对应 y = 2x + 1,是一条实线,默认颜色,down 对应 y = x^2^ ,虚线,红色,最后调用 legend 方法设置一些样式即可。

# 设置 legend 图例
l1,=plt.plot(x,y1,label='linear line')
l2,=plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='square line')

plt.legend()
复制代码

不带参数调用 legend 会自动获取图例句柄及相关标签,此函数等同于:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
复制代码

为完全控制要添加的图例句柄,通常将适当的句柄直接传递给 legend:

plt.legend(handles=[l1, l2])
复制代码

在某些情况下,我们需要为 legend 图例设置标签

plt.legend(handles=[l1, l2], labels=['up', 'down'])
复制代码

图例的位置

图例的位置可以通过关键字参数loc指定。 bbox_to_anchor关键字可让用户手动控制图例布局。 例如,如果你希望轴域图例位于图像的右上角而不是轴域的边角,则只需指定角的位置以及该位置的坐标系:

当我们指定 loc = 'upper right',legend 图例将在右上角展示:

你还可以指定 loc 在任何你想要指定的位置:

plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='lower right')
复制代码

loc 使用参数

整数,字符串或浮点偶对,默认为 'upper right'。

Legend 常见参数速查表
KeywordDescription
locLocation code string, or tuple (see below)
fontsizethe font size (used only if prop is not specified)
propthe font property
markerscalethe relative size of legend markers vs. original
markerfirstIf True (default), marker is to left of the label
numpointsthe number of points in the legend for line
scatterpointshe number of points in the legend for scatter plot
scatteroffsetsa list of yoffsets for scatter symbols in legend
frameonIf True, draw the legend on a patch (frame)
shadowIf True, draw a shadow behind legend
framealphaTransparency of the frame
edgecolorFrame edgecolor
facecolorFrame facecolor
fancyboxIf True, draw the frame with a round fancybox
ncolnumber of columns
borderpadthe fractional whitespace inside the legend border
handlelengththe length of the legend hendles
handletextpadThe pad between the legend handle and text
borderaxespadthe pad between the axes and legend border
columnspacingthe spacing between columns
titlethe legend title
bbox_to_anchorthe bbox that the legend will be anchored
bbox_tansformthe transform for the bbox,transAxes if None
图例处理器

为了创建图例条目,将句柄作为参数提供给适当的HandlerBase子类。 处理器子类的选择

有以下规则确定:

  • 使用handler_map关键字中的值更新get_legend_handler_map()
  • 检查句柄是否在新创建的handler_map中。
  • 检查句柄的类型是否在新创建的handler_map中。
  • 检查句柄的mro中的任何类型是否在新创建的handler_map中。

处于完整性,这个逻辑大多在get_legend_handler()中实现。

为了简单起见,让我们选择matplotlib.legend_handler.HandlerLine2D,它接受numpoints参数(出于便利,注意numpointslegend()函数上的一个关键字)。 然后我们可以将实例的字典作为关键字handler_map传给legend

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

# 设置legend图例
l1,=plt.plot(x,y1,marker = 'o',label='linear line')
l2,=plt.plot(x,y2,color='red',linewidth=1.0,marker = 'o',label='square line')

plt.legend(handler_map = {l1:HandlerLine2D(numpoints=4)},handles=[l1, l2], labels=['up', 'down'],  loc='lower right')
复制代码

如你所见,up现在有 4 个标记点,down有两个(默认值)。

推荐阅读

你需要的「 认知与技术 」福利

Python 学习之进程与线程 「 上 」

来北京的日子

这么多年都白学了,原来是方法没有用对

贝斯狸的 Python 之旅 -- 深入切片操作及原理

墙裂推荐 Anaconda | 安利 Python IDE

编程界的半壁江山

PS

特别抱歉,本周事情有点多,一直没有来得及更新。

这周经历了太多的事情:

1、在上海为了退房租,和房东大吵,报警,协商,最终还是我输了,好无奈。【请广大上班族在租房子的时候一定要看好合同,别让奸商有机可乘】

2、回家看爸妈,房租退了,准备来北京,所以在家呆了两三天,帮爸妈做点力所能及的事情。

3、踏上北京的征程,今天已经是在北京的第二天,心情自然是激动而喜悦的,对未来充满期待。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值