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

相关文章

Java中的getBytes()方法使用详解

《Java中的getBytes()方法使用详解》:本文主要介绍Java中getBytes()方法使用的相关资料,getBytes()方法有多个重载形式,可以根据需要指定字符集来进行转换,文中通过代... 目录前言一、常见重载形式二、示例代码三、getBytes(Charset charset)和getByt

Java使用Stream流的Lambda语法进行List转Map的操作方式

《Java使用Stream流的Lambda语法进行List转Map的操作方式》:本文主要介绍Java使用Stream流的Lambda语法进行List转Map的操作方式,具有很好的参考价值,希望对大... 目录背景Stream流的Lambda语法应用实例1、定义要操作的UserDto2、ListChina编程转成M

Spring框架中@Lazy延迟加载原理和使用详解

《Spring框架中@Lazy延迟加载原理和使用详解》:本文主要介绍Spring框架中@Lazy延迟加载原理和使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、@Lazy延迟加载原理1.延迟加载原理1.1 @Lazy三种配置方法1.2 @Component

使用easy connect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题

《使用easyconnect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题》:本文主要介绍使用easyconnect之后,maven无法... 目录使用easGWowCy connect之后,maven无法使用,原来需要配置-DJava.net.pr

使用Java编写一个字符脱敏工具类

《使用Java编写一个字符脱敏工具类》这篇文章主要为大家详细介绍了如何使用Java编写一个字符脱敏工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、字符脱敏工具类2、测试工具类3、测试结果1、字符脱敏工具类import lombok.extern.slf4j.Slf4j

pandas DataFrame keys的使用小结

《pandasDataFramekeys的使用小结》pandas.DataFrame.keys()方法返回DataFrame的列名,类似于字典的键,本文主要介绍了pandasDataFrameke... 目录Pandas2.2 DataFrameIndexing, iterationpandas.DataF

使用Python和PaddleOCR实现图文识别的代码和步骤

《使用Python和PaddleOCR实现图文识别的代码和步骤》在当今数字化时代,图文识别技术的应用越来越广泛,如文档数字化、信息提取等,PaddleOCR是百度开源的一款强大的OCR工具包,它集成了... 目录一、引言二、环境准备2.1 安装 python2.2 安装 PaddlePaddle2.3 安装

嵌入式Linux之使用设备树驱动GPIO的实现方式

《嵌入式Linux之使用设备树驱动GPIO的实现方式》:本文主要介绍嵌入式Linux之使用设备树驱动GPIO的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、设备树配置1.1 添加 pinctrl 节点1.2 添加 LED 设备节点二、编写驱动程序2.1

使用Python开发Markdown兼容公式格式转换工具

《使用Python开发Markdown兼容公式格式转换工具》在技术写作中我们经常遇到公式格式问题,例如MathML无法显示,LaTeX格式错乱等,所以本文我们将使用Python开发Markdown兼容... 目录一、工具背景二、环境配置(Windows 10/11)1. 创建conda环境2. 获取XSLT

Python中Flask模板的使用与高级技巧详解

《Python中Flask模板的使用与高级技巧详解》在Web开发中,直接将HTML代码写在Python文件中会导致诸多问题,Flask内置了Jinja2模板引擎,完美解决了这些问题,下面我们就来看看F... 目录一、模板渲染基础1.1 为什么需要模板引擎1.2 第一个模板渲染示例1.3 模板渲染原理二、模板