在这种情况下,您需要手动指定图例的艺术家和标签,或者使用ax.add_patch 而不是ax.add_artist。
legend 检查一些特定的艺术家列表来决定添加什么。诸如ax.lines、ax.collections、ax.patches 之类的东西。
ax.add_artist 是对任何类型艺术家的低级调用。它通常用于添加您不想在图例中添加的内容。但是,add_<foo> 变体使用add_artist 添加艺术家,然后将其附加到适当的列表中。因此,使用ax.add_patch 会将艺术家附加到ax.patches,然后legend 将对其进行检查。
或者,您可以手动指定艺术家列表和标签列表到ax.legend,以覆盖它自动检查的内容。
换句话说,你要么需要调用类似的东西:
ax.legend(ells, ['label1', 'label2', 'label3'])
或者做:
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.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()
手动指定艺术家和图例标签:
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()
两者产生相同的结果: