matplotlib:利用legend_handler模块在图例中插入图片(二)

《matplotlib:利用legend_handler模块在图例中插入图片》简单介绍了如何创建HandlerBase类的子类在图例中插入图片。

根据官方文档https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html,通过创建自定义类构造legend_artist方法也可以自由地在图例中插入图片。

效果

在这里插入图片描述

代码

import os

import matplotlib as mpl
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
from matplotlib.transforms import TransformedBbox, Bbox
from matplotlib.image import BboxImage

# 构造代理对象类
class AnyObject:
    pass

# 定义处理器
class ImageHandler:
    def __init__(self, image_path, image_stretch=(0, 0)):
        if os.path.exists(image_path):
            self.image_data = plt.imread(image_path)
        self.image_stretch = image_stretch

    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        width, height = handlebox.width, handlebox.height
        # 缩放图像
        sx, sy = self.image_stretch
        # 创建边框用于放置图像
        bb = Bbox.from_bounds(x0 - sx, y0 - sy, width + sx, height + sy)
        bbox = TransformedBbox(bb, handlebox.get_transform())
        image = BboxImage(bbox)
        image.set_data(self.image_data)
        handlebox.add_artist(image)
        return image


# 获取matplotlib数据目录mpl-data
data_path = mpl.get_data_path()
# 构造自定义图例处理器
custom_handler1 = ImageHandler(data_path + r"\images\home.png")
# 构造自定义图例处理器
custom_handler2 = ImageHandler(data_path + r"\images\back.png")
# 构造代理对象
s1 = AnyObject()
s2 = AnyObject()
# 添加图例,通过handler_map参数添加自定义映射
plt.legend([s1, s2], ['First', 'Second'],
           handler_map={s1: custom_handler1, s2: custom_handler2})

plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值