2

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.

Peaceful
  • 4,920
  • 15
  • 54
  • 79
  • 1
    Specifically, the second part of [this answer](https://stackoverflow.com/questions/44098362/using-mpatches-patch-for-a-custom-legend/44098900#44098900). Also, in the second example you are using `fig.legend` rather than `plt.legend` – DavidG Aug 31 '18 at 08:31
  • @DavidG This is helpful but doesn't directly answer my question: what is wrong with my code? – Peaceful Aug 31 '18 at 08:33
  • 1
    It's because not all artists can be added to the legend using `plt.legend(handles=)`. Seems that a circle patch is one of them, so a more detailed approach must be used. The [legend documentation](https://matplotlib.org/users/legend_guide.html) is a good read, and [this](https://matplotlib.org/users/legend_guide.html#implementing-a-custom-legend-handler) specific part too – DavidG Aug 31 '18 at 08:42
  • Hmm. I actually saw this before posting but couldn't understand several things: what are those two classes doing? Why do they derive from `object`? What is a `handlebox`, and so on. Could you simplify these a bit for me? – Peaceful Aug 31 '18 at 08:47
  • You need to implement a custom handler, see https://matplotlib.org/2.0.2/users/legend_guide.html#implementing-a-custom-legend-handler – 5norre Feb 23 '22 at 12:09

1 Answers1

11

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

SpghttCd
  • 10,510
  • 2
  • 20
  • 25
  • The problem with this solution is that Line2D has no `hatch` argument. So a Patch-like solution as requested in the question is still missing :/ – Martin Apr 05 '22 at 10:44