创建一个 matplotlib mpatches ,其中带有双色矩形作为图形图例

Giu*_*ora 3 python matplotlib python-3.x

我需要为 matplotlib 图中的图例创建一个补丁,其句柄框是一个具有两种颜色的矩形。像这样的东西,是我用油漆处理、切割和着色制作的:在此输入图像描述

你能告诉我如何以及从哪里开始吗?谢谢。

Imp*_*est 5

您当然可以从matplotlib legend 指南开始;更具体地说,在关于实现自定义处理程序的部分。

阅读有关自定义图例的其他一些问题,例如

也可能有帮助。

在这里,您想在图例中放置两个矩形。因此,在自定义Handler类中,您可以创建它们并将它们添加到handlebox.

import matplotlib.pyplot as plt

class Handler(object):
    def __init__(self, color):
        self.color=color
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        width, height = handlebox.width, handlebox.height
        patch = plt.Rectangle([x0, y0], width, height, facecolor='blue',
                                   edgecolor='k', transform=handlebox.get_transform())
        patch2 = plt.Rectangle([x0+width/2., y0], width/2., height, facecolor=self.color,
                                   edgecolor='k', transform=handlebox.get_transform())
        handlebox.add_artist(patch)
        handlebox.add_artist(patch2)
        return patch


plt.gca()

handles = [plt.Rectangle((0,0),1,1) for i  in range(4)]
colors = ["limegreen", "red", "gold", "blue"]
hmap = dict(zip(handles, [Handler(color) for color in colors] ))

plt.legend(handles=handles, labels=colors, handler_map=hmap)

plt.show()
Run Code Online (Sandbox Code Playgroud)

自定义图例中的两个矩形