【发布时间】:2018-04-27 11:39:34
【问题描述】:
我想用 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()
我认为这段代码等同于这里使用的方法How to add legend/label in python animation,但显然我遗漏了一些东西。
我也尝试按照Add a legend for an animation (of Artists) in matplotlib 中的建议设置标签,但我并不真正了解如何在我的情况下使用它。像这样
im2[sp-1].legend(handles='-', labels=[lab])
我收到了AttributeError: 'Line2D' object has no attribute 'legend'。
[编辑]:我没有说清楚:我想在图中的两条线都有一个图例。
【问题讨论】:
标签: python animation matplotlib legend subplot