python - 用图像替换 Matplotlib 图例的标签

标签 python image matplotlib legend

我想在图例中使用图像而不是标签。

例如,我画了 2 条线并显示了一个图例:

import matplotlib.pyplot as plt
plt.plot([1,2],label="first_image")
plt.plot([2,1],label="second_image")
plt.legend()
plot.show()

What I have now

但我想要这样的东西:

The result I need

请注意,这不是 Insert image in matplotlib legend 的副本, 我的问题是“将标签更改为图片”,而另一个问题是“将图例的符号更改为图片”

最佳答案

在图例中创建图像的概念已在这个问题 (Insert image in matplotlib legend) 中提出,其中图像用作图例条目的艺术家。

如果您想要图例中的线条句柄和图像,我们的想法是创建一个由两者组成的句柄,并彼此相邻放置。 唯一的问题是微调参数,使其看起来更吸引人。

import matplotlib.pyplot as plt
import matplotlib.lines
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.legend_handler import HandlerBase
from matplotlib.image import BboxImage

class HandlerLineImage(HandlerBase):

    def __init__(self, path, space=15, offset = 10 ):
        self.space=space
        self.offset=offset
        self.image_data = plt.imread(path)        
        super(HandlerLineImage, self).__init__()

    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):

        l = matplotlib.lines.Line2D([xdescent+self.offset,xdescent+(width-self.space)/3.+self.offset],
                                     [ydescent+height/2., ydescent+height/2.])
        l.update_from(orig_handle)
        l.set_clip_on(False)
        l.set_transform(trans)

        bb = Bbox.from_bounds(xdescent +(width+self.space)/3.+self.offset,
                              ydescent,
                              height*self.image_data.shape[1]/self.image_data.shape[0],
                              height)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)
        return [l,image]


plt.figure(figsize=(4.8,3.2))
line,  = plt.plot([1,2],[1.5,3], color="#1f66e0", lw=1.3)
line2,  = plt.plot([1,2],[1,2], color="#efe400", lw=1.3)
plt.ylabel("Flower power")

plt.legend([line, line2], ["", ""],
   handler_map={ line: HandlerLineImage("icon1.png"), line2: HandlerLineImage("icon2.png")}, 
   handlelength=2, labelspacing=0.0, fontsize=36, borderpad=0.15, loc=2, 
    handletextpad=0.2, borderaxespad=0.15)

plt.show()

enter image description here

关于python - 用图像替换 Matplotlib 图例的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42155119/

相关文章:

python - Riak Search 2 没有索引桶

python - 如何为按时间排序的 matplotlib 图序列制作动画

java - 图像调整大小以适应 JPanel

python - 如何在 Django Web 应用程序中渲染 Matplotlib 绘图?

Python 3.3 - 从规则间隔的顶点创建 3D 网格作为 Wavefront obj 文件

python - Pylint 错误 E1128 背后的逻辑(无分配)

python - Python2.7中使用requests时出错

image - Wordpress media_sideload_image - 下载 http ://placekitten. com/100/100?

python - 密度与频率

python - 更改图表边框区域颜色