matplotlib学习笔记--Legend

2024-05-07 17:08

本文主要是介绍matplotlib学习笔记--Legend,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

legend 显示图例

1 legend基础

函数原型 legend(*args, **kwargs) 

len(args) == 2

       args [artist][label]的集合

len(args) == 0

       args会自动调用get_legend_handles_labels()生成

       等价于

       handles, labels = ax.get_legend_handles_labels()

      ax.legend(handles, labels)

ax.get_legend_handles_labels()的作用在于返回ax.lines, ax.patch所有对象以及ax.collection中的LineCollection or RegularPolyCollection对象

     注意:这里只提供有限支持, 并不是所有的artist都可以被用作图例,比如errorbar支持不完善

 

1.1 调整顺序

ax = subplot(1,1,1)

p1, = ax.plot([1,2,3], label="line 1")

p2, = ax.plot([3,2,1], label="line 2")

p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order

ax.legend(handles[::-1], labels[::-1])

 

matplotlib学习笔记--Legend

# or sort them by labels

import operator
hl = sorted(zip(handles, labels), key=operator.itemgetter(1))

handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

matplotlib学习笔记--Legend


1.2 使用代理artist

当需要使用legend不支持的artist时,可以使用另一个被legend支持的artist作为代理

比如以下示例中使用不在axe上的一个artist

= Rectangle((0, 0), 1, 1, fc="r")

legend([p], ["Red Rectangle"])

 

2 多列图例

ax1 = plt.subplot(3,1,1)

ax1.plot([1], label="multi\nline")

ax1.plot([1], label="$2^{2^2}$")

ax1.plot([1], label=r"$\frac{1}{2}\pi$")

ax1.legend(loc=1, ncol=3, shadow=True)

 

ax2 = plt.subplot(3,1,2)

myplot(ax2)

ax2.legend(loc="center left", bbox_to_anchor=[0.50.5],

           ncol=2, shadow=True, title="Legend")

ax2.get_legend().get_title().set_color("red")

 

matplotlib学习笔记--Legend

 

 

3 图例位置

 

ax.legend(., loc=3) 具体对应位置如下图

matplotlib学习笔记--Legend

绘制在图上是这样的,(具体没有分清 57的区别)

matplotlib学习笔记--Legend

4 多个图例

如果不采取措施,连续调用两个legend会使得后面的legend覆盖前面的

 

from matplotlib.pyplot import * p1, = plot([1,2,3], label="test1")

p2, = plot([3,2,1], label="test2")

l1 = legend([p1], ["Label 1"], loc=1)
l2 = legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.

gca().add_artist(l1) # add l1 as a separate artist to the axes

 

5. API

class matplotlib.legend.Legend(parent, handles, labels,**args)

三个最重要的必要参数

parent --- legend的父artist, 包含legend的对象

       比如用ax.legend()调用之后

       >>> print ax.get_legend().parent

       Axes(0.125,0.1;0.775x0.8)

handles --- 图例上面画出的各个artistlines, patches

labels --- artist 对应的标签

其他参数 

 

Keyword

Description

loc

a location code

prop

the font property (matplotlib.font_manager.FontProperties 对象)

eg

song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8)

fontsize

the font size (prop互斥,不可同时使用)

markerscale

the relative size of legend markers vs. original

numpoints

the number of points in the legend for line

scatterpoints

the number of points in the legend for scatter plot

scatteryoffsets

a list of yoffsets for scatter symbols in legend

frameon

if True, draw a frame around the legend. If None, use rc

fancybox

if True, draw a frame with a round fancybox. If None, use rc

shadow

if True, draw a shadow behind legend

ncol

number of columns

borderpad

the fractional whitespace inside the legend border

labelspacing

the vertical space between the legend entries

handlelength

the length of the legend handles

handleheight

the length of the legend handles

handletextpad

the pad between the legend handle and text

borderaxespad

the pad between the axes and legend border

columnspacing

the spacing between columns

title

the legend title

bbox_to_anchor

the bbox that the legend will be anchored.

bbox_transform

the transform for the bbox. transAxes if None.


主要函数

get_frame() ---  返回legend所在的方形对象

get_lines()

get_patches()

get_texts()

get_title() ---  上面几个比较简单,不解释了

set_bbox_to_anchor(bbox, transform=None)

(…本函数待续之后写axes的时候会加入,目前我没有看懂他的这个长宽和figure以及axes的关系)

 

6. 样例

matplotlib学习笔记--Legend

leg = ax.legend(('Model length''Data length''Total message length'),

           'upper center', shadow=True)

# the matplotlib.patches.Rectangle instance surrounding the legend 即外框

frame  = leg.get_frame()

frame.set_facecolor('0.80'   # set the frame face color to light gray

 

# matplotlib.text.Text instances legend中文本

for in leg.get_texts():

    t.set_fontsize('small'   # the legend text fontsize

 

# matplotlib.lines.Line2D instances legend中所表示的artist

for in leg.get_lines():

    l.set_linewidth(1.5 # the legend line width

 

matplotlib学习笔记--Legend

fig = plt.figure()

ax1 = fig.add_axes([0.10.10.40.7])

ax2 = fig.add_axes([0.550.10.40.7])

 

= np.arange(0.02.00.02)

y1 = np.sin(2*np.pi*x)

y2 = np.exp(-x)

l1, l2 = ax1.plot(x, y1, 'rs-', x, y2, 'go')

 

y3 = np.sin(4*np.pi*x)

y4 = np.exp(-2*x)

l3, l4 = ax2.plot(x, y3, 'yd-', x, y3, 'k^')

 

fig.legend((l1, l2), ('Line 1''Line 2'), 'upper left')

fig.legend((l3, l4), ('Line 3''Line 4'), 'upper right')

这篇关于matplotlib学习笔记--Legend的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/967890

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

线性代数|机器学习-P36在图中找聚类

文章目录 1. 常见图结构2. 谱聚类 感觉后面几节课的内容跨越太大,需要补充太多的知识点,教授讲得内容跨越较大,一般一节课的内容是书本上的一章节内容,所以看视频比较吃力,需要先预习课本内容后才能够很好的理解教授讲解的知识点。 1. 常见图结构 假设我们有如下图结构: Adjacency Matrix:行和列表示的是节点的位置,A[i,j]表示的第 i 个节点和第 j 个

Node.js学习记录(二)

目录 一、express 1、初识express 2、安装express 3、创建并启动web服务器 4、监听 GET&POST 请求、响应内容给客户端 5、获取URL中携带的查询参数 6、获取URL中动态参数 7、静态资源托管 二、工具nodemon 三、express路由 1、express中路由 2、路由的匹配 3、路由模块化 4、路由模块添加前缀 四、中间件