本文介绍了创建一个带有双色矩形的 matplotlib mpatches 用于图形图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为 matplotlib 图形中的图例创建一个补丁,其手柄框是一个具有两种颜色的矩形.像这样的东西,我用油漆处理,切割和着色:

i need to create a patch for a legend in a matplotlib figure whose handlebox is a a rectangle with two color. something like this, that i have made with paint coping, cutting and coloring:

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

Can you tell me how and where to start?Thanks.

推荐答案

您当然会从开始matplotlib图例指南;更具体地说,在关于实现自定义处理程序的部分.

You would of course start at the matplotlib legend guide; more specifically at the section about implementing a custom handler.

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

Reading some other questions on customizing the legend, like

可能也有帮助.

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

Here you want to put two rectangles in the legend. So inside a custom Handler class, you can create those and add them to the 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()

这篇关于创建一个带有双色矩形的 matplotlib mpatches 用于图形图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!