I'm sure this is a basic question, but I can't find the solution. I'm plotting some ellipses and would like to add a legend (something like color of first ellipse: data 1,...) At the moment I manage to plot some ellipses, but I don't get how to do the legend.
My code:
from pylab import figure, show, rand
from matplotlib.patches import Ellipse
NUM = 3
ells = [Ellipse(xy=rand(2)*10, width=rand(), height=rand(), angle=rand()*360)
for i in range(NUM)]
fig = figure()
ax = fig.add_subplot(111, aspect='equal')
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(rand())
e.set_facecolor(rand(3))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
show()
In this case, you'll need to either specify the legend's artists and labels manually or use ax.add_patch instead of ax.add_artist.
legend checks a few particular lists of artists to decide what to add. Things like ax.lines, ax.collections, ax.patches, etc.
ax.add_artist is a low-level call for any type of artist. It's often used to add things that you wouldn't want in a legend. However, the add_<foo> variants add the artist using add_artist, but then append it to the appropriate list. Therefore, using ax.add_patch will append the artist to ax.patches, which legend will then check.
Alternatively, you can manually specify a list of artists and a list of labels to ax.legend to override what it automatically checks for.
In other words, you'll either need to call something similar to:
ax.legend(ells, ['label1', 'label2', 'label3'])
or do:
for i, e in enumerate(ells):
ax.add_patch(e)
e.set(clip_box=ax.bbox, alpha=rand(), facecolor=rand(3),
label='Ellipse{}'.format(i+1))
ax.legend()
As a full example of using ax.add_patch:
from numpy.random import rand
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
NUM = 3
ellipse = lambda: Ellipse(rand(2)*10, rand(), rand(), rand()*360)
ells = [ellipse() for i in range(NUM)]
fig, ax = plt.subplots()
for i, e in enumerate(ells):
ax.add_patch(e)
e.set(clip_box=ax.bbox, alpha=rand(), facecolor=rand(3),
label='Ellipse{}'.format(i+1))
ax.legend()
ax.set(xlim=[0, 10], ylim=[0, 10], aspect='equal')
plt.show()
And of manually specifying the artists and legend labels:
from numpy.random import rand
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
NUM = 3
ellipse = lambda: Ellipse(rand(2)*10, rand(), rand(), rand()*360)
ells = [ellipse() for i in range(NUM)]
fig, ax = plt.subplots()
for e in ells:
ax.add_artist(e)
e.set(clip_box=ax.bbox, alpha=rand(), facecolor=rand(3))
ax.legend(ells, ['Ellipse{}'.format(i+1) for i in range(NUM)])
ax.set(xlim=[0, 10], ylim=[0, 10], aspect='equal')
plt.show()
Both produce identical results:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With