python中图例legend标签内容_Matplotlib 系列之「Legend 图例」

2023-04-26 14:16:42

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 常见参数速查表

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参数(出于便利,注意numpoints是legend()函数上的一个关键字)。 然后我们可以将实例的字典作为关键字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有两个(默认值)。

好书推荐

程序员的数学

豆瓣简介

如果数学不好,是否可以成为一名程序员呢?答案是肯定的。 本书最适合:数学糟糕但又想学习编程的你。

没有晦涩的公式,只有好玩的数学题。

帮你掌握编程所需的“数学思维”。

编程的基础是计算机科学,而计算机科学的基础是数学。因此,学习数学有助于巩固编程的基础,写出更健壮的程序。

本书面向程序员介绍了编程中常用的数学知识,借以培养初级程序员的数学思维。读者无需精通编程,也无需精通数学,只需具备四则运算和乘方等基础知识,就可以阅读本书。

书中讲 解了二进制计数法、逻辑、余数、排列组合、递归、指数爆炸、不可解问题等许多与编程密切相关的数学方法,分析了哥尼斯堡七桥问题、少年高斯求和方法、汉诺塔、斐波那契数列等经典问题和算法。引导读者深入理解编程中的数学方法和思路。

本书还对程序员和计算机的分工进行了有益的探讨。读完此书,你会对以程序为媒介的人机合作有更深刻的理解。

学习之道

豆瓣简介

读完一本书,却不记得讲什么?

美剧看了一箩筐,英语还是没长进?

公众号、指导书、牛人帖,一个都没落,却还是没有形成自己的学习体系?

这些都是典型的低质量学习症状。 不了解学习的原理,就是在无效重复;缺乏有效的学习方法,就是在消耗天赋。

本书从脑科学和心理学的最新研究出发,跨学科解读学习的原理,提供最全面的学习方法和思维模式: 大脑如何处理图形、文字、数字等信息,不同类型的学习匹配哪种信息通路 学艺术、学语言、学音乐、学数理??

各种事物的学习原理有何差异 对于你而言,为什么 A 方法比 B 方法效果更好 如果你翻开这本书,我相信你对学习是认真的。

  • 作者:weixin_39596975
  • 原文链接:https://blog.csdn.net/weixin_39596975/article/details/110027002
    更新时间:2023-04-26 14:16:42