标签绘制的椭圆

时间:2015-09-17 12:54:39

标签: 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()*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()

1 个答案:

答案 0 :(得分:4)

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

legend检查一些特定的艺术家名单,以决定添加什么。 ax.linesax.collectionsax.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()

两者产生相同的结果:

enter image description here

相关问题