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**2plt.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 常见参数速查表

KeywordDescriptionlocLocation code string, or tuple (see below)fontsizethe font size (used only if prop is not specified)propthe font propertymarkerscalethe relative size of legend markers vs. originalmarkerfirstIf True (default), marker is to left of the labelnumpointsthe number of points in the legend for linescatterpointshe number of points in the legend for scatter plotscatteroffsetsa list of yoffsets for scatter symbols in legendframeonIf True, draw the legend on a patch (frame)shadowIf True, draw a shadow behind legendframealphaTransparency of the frameedgecolorFrame edgecolorfacecolorFrame facecolorfancyboxIf True, draw the frame with a round fancyboxncolnumber of columnsborderpadthe fractional whitespace inside the legend borderhandlelengththe length of the legend hendleshandletextpadThe pad between the legend handle and textborderaxespadthe pad between the axes and legend bordercolumnspacingthe spacing between columnstitlethe legend titlebbox_to_anchorthe bbox that the legend will be anchoredbbox_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有两个(默认值)。

参考

1. Matplotlib 系列之「Legend 图例」 - 知乎

【Matplotlib】(二)图例legend相关推荐

  1. 调整matplotlib的图例legend的位置

    很多时候再用matplotlib画图例时,直接使用的是: plt.legend(lab) 以为它会自动调整图例的位置,今天画了个雷达图,发现图例位置和想象中的不一样,如下: 经查资料,原来可以lege ...

  2. 【matplotlib】饼图+legend()、loc、color位置颜色图例中文显示(一个饼图的例子)

    博客已经搬家到"捕获完成": https://www.v2python.com 1.原来自己做的饼图:http://mp.blog.csdn.net/postedit/792221 ...

  3. matplotlib命令与格式:图例legend语法及设置

    1.图例legend基础语法及用法 legend语法参数如下: matplotlib.pyplot.legend(*args, **kwargs) (1)设置图例位置 使用loc参数 plt.lege ...

  4. python怎么定义正方形函数_python – Matplotlib自定义图例以显示正方形而不是矩形...

    这是我尝试将条形图的图例从矩形更改为方形: import matplotlib.patches as patches rect1 = patches.Rectangle((0,0),1,1,facec ...

  5. legend函数_ggplot的图例(legend)管理

     如果你也想做统计分析,请关注我一起进步! 一.简介 ggplot2是R中最重要的作图包,没有之一!ggplot2是基于图形语法开发而成的,它以声明的方式创建图形.用户只需要提供数据.指明如何投影变量 ...

  6. html中legend样式,echarts自定义图例legend文字和样式

    话不多说,先上效果图. 要完成这个图并不难,主要是下面那个图例比较难,需要定制. 让我们从官方文档找找思路,官方文档关于legend.formatter是这样的:链接在这 难点在于: 1.这里的图例文 ...

  7. R语言可视化包ggplot2改变图例(legend)的标题(title)实战

    R语言可视化包ggplot2改变图例(legend)的标题(title)实战 目录 R语言可视化包ggplot2改变图例(legend)的标题(title)实战

  8. R语言可视化包ggplot2改变图例(legend)元素的大小实战:包含图例中标题字体、文本字体、标识模块(key)的大小

    R语言可视化包ggplot2改变图例(legend)元素的大小实战:包含图例中标题字体.文本字体.标识模块(key)的大小 目录

  9. R语言可视化包ggplot2改变图例(legend)标签实战

    R语言可视化包ggplot2改变图例(legend)标签实战 目录 R语言可视化包ggplot2改变图例(legend)的标签实战 #ggplot2图例标签改变语法

  10. python 2: 解决python中的plot函数的图例legend不能显示中文问题

    python 2: 解决python中的plot函数的图例legend不能显示中文问题 参考文章: (1)python 2: 解决python中的plot函数的图例legend不能显示中文问题 (2) ...

最新文章

  1. [转载]C# ListT的并集、交集、差集
  2. [转]MFC下关于“建立空文档失败”问题的分析
  3. Oracle SID爆破工具SidGuess
  4. python 上传文件夹,python – 使用Flask上传文件夹/文件
  5. Python基础概念_11_标准库
  6. endnote修改正文中参考文献标注_请问endnote里,如何把正文中插入参考文献处的格式由数字转为(作者,年份)?感恩!...
  7. Dart编译技术在服务端的探索和应用
  8. android群英传神兵利器pdf,《Android群英传:神兵利器》勘误
  9. Oracle 10g、11g :RAC关闭、启动、重启步骤
  10. 人机交互,情感计算,,人工智能相关研究的科研团队
  11. Python 创建本地服务器环境生成二维码
  12. uni —app 录音_uniapp如何实现录音功能
  13. GitHub上超火的“算法宝典”,程序员开发指南
  14. Gamemaker小课堂#0 如何为 Windows 游戏编写 DLL 扩展
  15. 加密数据库与密文检索、同态加密
  16. 商城 商品模块 数据库 表设计
  17. 今日头屏app v1.0.80
  18. 关于单边账的解释及解决(收单行业)
  19. Mixly23:U型红外光电开关
  20. python的读后感_《笨办法学python》读后感

热门文章

  1. 不平衡数据分类实证-R语言
  2. 统计学三大相关系数之Pearson相关系数、Spearman相关系数
  3. mac 10.13.6 升级至10.14.6再升级至12.4
  4. mac升级编译器gcc方法
  5. 爬虫晋江小说python_python 爬虫入门之爬小说
  6. html压缩包怎么打开,展示电脑rar压缩包文件怎么打开?教你正确打开方式
  7. guzzlehttp
  8. oracle 压缩备份比率,Oracle 10g备份集压缩(Backupset Compression)
  9. Html页面上展示Excel表格 --Handsontable
  10. tcp转发器使用说明