创建一个带有双色矩形的matplotlib mpatches用于图例

时间:2017-06-01 14:54:15

标签: python python-3.x matplotlib

我需要在matplotlib图中为图例创建一个补丁,其手柄框是一个有两种颜色的矩形。像这样的东西,我用油漆应对,切割和着色做的:enter image description here

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

1 个答案:

答案 0 :(得分:2)

你当然会从matplotlib legend guide开始;更具体地说,在关于implementing a custom handler的部分。

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

也可以提供帮助。

在这里,您要在图例中放置两个矩形。因此,在自定义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()

two rectangles in custom legend