Search code examples
pythonmatplotliblegendlegend-properties

Circle in the legend handle doesn't work in matplotlib


I am on Ubuntu 18.04 and my matplotlib version is 2.1.1. I am trying to plot a circular patch as a figure legend handle. This example gives a way of using customized handles like this:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()

But I want a circular handle instead of a rectangular patch. So I tried:

import matplotlib.pyplot as plt import matplotlib.patches as mpatches

fig, ax = plt.subplots(1, 1)
circle = mpatches.Circle(xy = (0.5, 0.5), radius = 100,color = "green")

ax.plot([1, 2, 3], [1, 2, 3])

fig.legend(handles = [circle], labels = ["some funny label"])
plt.show()

However, I still get a rectangular patch, and in my opinion, in a wrong location. What exactly am I missing?

enter image description here

Edit : I am specifically asking what is wrong with my code. It is helpful to have workarounds but I don't see anything wrong with the code above.


Solution

  • In the docs they do this as follows:

    from matplotlib.lines import Line2D
    import matplotlib.pyplot as plt
    
    red_circle = Line2D([0], [0], marker='o', color='w', label='Circle',
                            markerfacecolor='r', markersize=15),
    plt.legend(handles=red_circle)
    

    enter image description here