using mpatches.Patch for a custom legend

Viewed 33836

I'm using the following code to create a custom matplotlib legend.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
patches = [ mpatches.Patch(color=colors[i], label="{:s}".format(texts[i]) ) for i in range(len(texts)) ]
plt.legend(handles=patches, bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2 )

The resulted legend is as follows:

enter image description here

1 - The white symbol in the legend is not shown because that the default legend background is white as well. How can I set the legend background to other color ?

2 - How to change the rectangular symbols in the legend into circular shape ?

3 Answers

As the other answers did not work for me, I am adding an answer that is super simple and straight forward:

import matplotlib.pyplot as plt
handles = []
for x in colors:
    handles.append(plt.Line2D([], [], color=x, marker="o", linewidth=0))

You can adjust marker size and whatever else you want (maybe a star etc) and the linewidth removes the line to leave you with only the marker. Works perfectly and is super simple!

Even simpler:

import matplotlib.pyplot as plt
handles = [(plt.Line2D([], [], color=x, marker="o", linewidth=0)) for x in colors]
Related