matplotlib图例使用案例1.1:在不同行或列的图例上添加title

2024-02-20 02:44

本文主要是介绍matplotlib图例使用案例1.1:在不同行或列的图例上添加title,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们将图例进行行显示或者列显示后,只能想继续赋予不同行或者列不同的title来进行分类。比较简单的方式,就是通过ax.annotate方法添加标签,这样方法复用率比较低,每次使用都要微调ax.annotate的显示位置。比较方便的方法是在案例1实现的基础上,添加title显示的功能。

motplotlib图例案例1:通过多个legend完全控制图例显示顺序(指定按行排序 or 按列排序)

添加title显示功能后的代码:

import matplotlib.pyplot as plt
import matplotlib.axes
from typing import List, Tuple, Any
#这个函数可以获得axis对象的已经绘制的artist中的所有的hander和labels,这个可以只给它一个axis参数。注意这个参数需要是列表类的。
from matplotlib.legend import _get_legend_handles_labels as get_legend_handles_labelsdef custom_legend_layout(axis: matplotlib.axes.Axes,handlers: List[Any]=None,labels: List[str]=None,n_items: int = 3,offset: float = 0.05,vertical: bool = False,loc: str = 'upper right',first_bbox_to_anchor: Tuple[float, float] = (1, 1),title:List[str]=None,title_shift:List[Tuple[float,float]]=None,**kwargs) -> None:"""A function to arrange legend items in a custom layout.:param axis: Axis object on which to place the legends.:param lines: List of line objects to include in the legends.:param labels: List of labels corresponding to the line objects.:param n_items: Number of items per row (if vertical=False) or column (if vertical=True).:param offset: Vertical offset between rows (or horizontal offset between columns if vertical=True).:param vertical: If True, legends are arranged vertically, otherwise horizontally.:param loc: Location anchor for all legends.:param first_bbox_to_anchor:  `~matplotlib.transforms.BboxBase` instance,Bbox anchor of the first legend.:param kwargs: Additional keyword arguments to pass to the legend function."""va_dict={"center":'center',"lower":'top',"upper":'bottom'}ha_dict={"center": 'center',"right":"left","left":"right",}if (handlers is None) != (labels is None):  # Check if only one of handlers or labels is providedraise ValueError("Both 'handlers' and 'labels' must be specified if one is provided.")if (handlers is None) and (labels is None): # get default handlers and labels from axhandlers,labels=get_legend_handles_labels(axs=[axis]) # note:  the param axs is list object# 确保n_items不为0,避免除以0的错误n_items = max(1, n_items)# 计算需要多少个图例n_legends = len(handlers) // n_items + (1 if len(handlers) % n_items else 0)# 计算每个图例的bbox_to_anchorfor i in range(n_legends):start_idx = i * n_itemsend_idx = min(start_idx + n_items, len(handlers))legend_lines = handlers[start_idx:end_idx]legend_labels = labels[start_idx:end_idx]if vertical:# 对于垂直布局ncol = 1if i == 0:bbox_anchor = first_bbox_to_anchorelse:# 计算后续图例的bbox_to_anchorbbox_anchor = (first_bbox_to_anchor[0] + i * offset, first_bbox_to_anchor[1])else:# 对于水平布局ncol = len(legend_lines)if i == 0:bbox_anchor = first_bbox_to_anchorelse:# 计算后续图例的bbox_to_anchorbbox_anchor = (first_bbox_to_anchor[0], first_bbox_to_anchor[1] - i * offset)legend = axis.legend(legend_lines, legend_labels, loc=loc, bbox_to_anchor=bbox_anchor, ncol=ncol, frameon=False, **kwargs)axis.add_artist(legend)# 计算每个title的位置va_key,ha_key=loc.split(" ")if title and len(title)==n_legends:w_shift= title_shift[i][0] if title_shift else 0h_shift=title_shift[i][1] if title_shift else 0axis.annotate(text=title[i],xy=(bbox_anchor[0]+w_shift, bbox_anchor[1]+h_shift),xycoords='axes fraction',va=va_dict[va_key],ha=ha_dict[ha_key])if __name__ == '__main__':# 示例使用这个函数fig, ax = plt.subplots()handlers = [ax.scatter(range(10), [i * x for x in range(10)], label=f'Line {i}') for i in range(7)]# 调用函数,横向排列图例custom_legend_layout(ax, n_items=3, offset=0.25, vertical=True,loc='upper left', first_bbox_to_anchor=(0.2, 0.8),title=["title 1","title 2","title 3"],#title_shift=[(-0.1,0),(-0.1,0),(-0.1,0)],)from matplotlib.legend import _get_legend_handles_labels as get_legend_handles_labelshandles,labels=get_legend_handles_labels([ax])plt.show()

运行后:

在这里插入图片描述

这篇关于matplotlib图例使用案例1.1:在不同行或列的图例上添加title的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期