Python 标绘椭圆

Python 标绘椭圆,python,matplotlib,legend,Python,Matplotlib,Legend,我肯定这是一个基本问题,但我找不到解决办法。 我正在绘制一些椭圆,并想添加一个类似的图例 第一个椭圆的颜色:数据1,。。。 目前,我设法画了一些椭圆,但我不知道如何做的传奇 我的代码: 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(

我肯定这是一个基本问题,但我找不到解决办法。 我正在绘制一些椭圆,并想添加一个类似的图例 第一个椭圆的颜色:数据1,。。。 目前,我设法画了一些椭圆,但我不知道如何做的传奇

我的代码:

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()

在这种情况下,您需要手动指定图例的艺术家和标签,或者使用ax.add_patch而不是ax.add_artist

legend会检查一些特定的艺术家列表,以决定添加什么。比如ax.line、ax.collection、ax.patches等等

ax.add_artist是对任何类型的艺术家的低级调用。它经常被用来在传奇中添加你不想要的东西。但是,“添加艺术家”变体使用“添加艺术家”添加艺术家,然后将其附加到相应的列表中。因此,使用ax.add_patch会将艺术家附加到ax.patches,然后图例会检查它

或者,您可以手动将艺术家列表和标签列表指定给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_补丁的完整示例:

以及手动指定艺术家和图例标签:

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()
两者产生相同的结果:

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()