《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()