标签绘制椭圆

kel*_*lia 3 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()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 5

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


legend检查一些特定的艺术家列表来决定添加什么。诸如ax.linesax.collectionsax.patches等之类的东西。

ax.add_artist是对任何类型的艺术家的低级呼吁。它通常用于添加您不想在图例中添加的内容。但是,add_<foo>变体使用 添加艺术家add_artist,然后将其附加到适当的列表中。因此,使用ax.add_patch会将艺术家附加到ax.patcheslegend然后进行检查。

或者,您可以手动指定艺术家列表和标签列表以ax.legend覆盖它自动检查的内容。


换句话说,您需要调用类似于以下内容的内容:

ax.legend(ells, ['label1', 'label2', 'label3'])
Run Code Online (Sandbox Code Playgroud)

或者做:

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()
Run Code Online (Sandbox Code Playgroud)

作为使用的完整示例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()
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

两者产生相同的结果:

在此输入图像描述