3

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: enter image description here

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

Community
  • 1
  • 1
Giuseppe Angora
  • 833
  • 1
  • 10
  • 25

1 Answers1

5

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

may also help.

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

two rectangles in custom legend

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712