如何为子图绘制动态图例?

4

我希望能够使用ArtistAnimation绘制动画子图。不幸的是,我无法弄清楚如何制作动态图例。我尝试了在StackOverflow上找到的不同方法。如果我设法获得一个图例,它就不是动态的,而只是所有动画步骤的图例。

我的代码看起来像这样:

import numpy as np
import pylab as pl
import matplotlib.animation as anim

fig, (ax1, ax2, ax3) = pl.subplots(1,3,figsize=(11,4))
ims   = []
im1   = ['im11','im12','im13']
im2   = ['im21','im22','im23']
x = np.arange(0,2*np.pi,0.1)

n=50
for i in range(n):
    for sp in (1,2,3):
        pl.subplot(1,3,sp)

        y1 = np.sin(sp*x + i*np.pi/n)
        y2 = np.cos(sp*x + i*np.pi/n)

        im1[sp-1], = pl.plot(x,y1)
        im2[sp-1], = pl.plot(x,y2)

        pl.xlim([0,2*np.pi])
        pl.ylim([-1,1])

        lab = 'i='+str(i)+', sp='+str(sp)
        im1[sp-1].set_label([lab])
        pl.legend(loc=2, prop={'size': 6}).draw_frame(False)

    ims.append([ im1[0],im1[1],im1[2], im2[0],im2[1],im2[2] ])

ani = anim.ArtistAnimation(fig,ims,blit=True)
pl.show()

这是结果的样子

我认为这段代码应该等同于这里使用的方法:如何在Python动画中添加图例/标签,但显然我错过了一些东西。

我也尝试按照在Matplotlib中为艺术家动画添加图例中建议的设置标签,但我不真正理解如何将其用于我的案例。像这样:

im2[sp-1].legend(handles='-', labels=[lab])

我遇到了一个AttributeError: 'Line2D' object has no attribute 'legend'错误。 [编辑]:我没有说清楚:我想在图表中为两条线都添加图例。
1个回答

4
我不知道传说应该长什么样,但我想你只是想让它显示当前帧的一行的当前值。因此,最好更新该行的数据,而不是绘制150个新图。
import numpy as np
import pylab as plt
import matplotlib.animation as anim

fig, axes = plt.subplots(1,3,figsize=(8,3))
ims   = []
im1   = [ax.plot([],[], label="label")[0] for ax in axes]
im2   = [ax.plot([],[], label="label")[0] for ax in axes]
x = np.arange(0,2*np.pi,0.1)

legs = [ax.legend(loc=2, prop={'size': 6})  for ax in axes]

for ax in axes:
    ax.set_xlim([0,2*np.pi])
    ax.set_ylim([-1,1])
plt.tight_layout()
n=50
def update(i):
    for sp in range(3):
        y1 = np.sin((sp+1)*x + (i)*np.pi/n)
        y2 = np.cos((sp+1)*x + (i)*np.pi/n)

        im1[sp].set_data(x,y1)
        im2[sp].set_data(x,y2)

        lab = 'i='+str(i)+', sp='+str(sp+1)
        legs[sp].texts[0].set_text(lab)
        legs[sp].texts[1].set_text(lab)

    return im1 + im2 +legs 

ani = anim.FuncAnimation(fig,update, frames=n,blit=True)
plt.show()

enter image description here


似乎我的最小示例有点太小了。 :) 我想为两条线都添加图例。我可以添加 legs2 并手动将其移动到正确的位置,但它不会自动与第二个(这里是橙色)数据相关联。到目前为止,我更喜欢循环版本(而不是使用 def),因为实际上,我正在处理具有 30000 个 i 的数据,并且必须跳过大部分数据。是否有一种方法在 update(i) 中包含类似于 continuebreak 条件? - Waterkant
1
使用frames=something给定的i调用update函数与循环for i in something是相同的。因此,我认为这没有任何问题。但是当然,您也可以从上面的代码创建一个ArtistAnimation,只需将图例添加到列表artists中即可。我在答案中更新了两个图例条目。 - ImportanceOfBeingErnest
我没有成功使用ArtistAnimation,但是使用带有全面列表的“frames=n”完成了工作。谢谢! - Waterkant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接