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

相关文章

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx