【问题标题】:Label plotted ellipses标注绘制的椭圆
【发布时间】:2015-09-17 12:54:38
【问题描述】:

我确定这是一个基本问题,但我找不到解决方案。 我正在绘制一些椭圆并想添加一个图例(类似于 第一个椭圆的颜色:数据 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()

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    在这种情况下,您需要手动指定图例的艺术家和标签,或者使用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()
    

    两者产生相同的结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多