【发布时间】:2021-04-29 16:34:48
【问题描述】:
我正在使用 matplotlib 在 python 中绘制一些动画散点图。我目前有这个代码:
def calulateStep():
# Math stuff ....
# Changes values in in 'circpos' Nx2 array
fig, ax = plt.subplots(figsize=(5, 5))
ax.set(xlim=(-WELLRADIUS,WELLRADIUS), ylim=(-WELLRADIUS,WELLRADIUS))
[x,y] = np.hsplit(circpos,2)
scat = ax.scatter(x.flatten(),y.flatten())
def animate(i):
calculateStep()
scat.set_offsets(circpos)
return scat,
anim = FuncAnimation(fig, animate, frames=60)
anim.save('test2.gif',writer='imagemagick')
plt.draw()
plt.show()
函数 calculateStep 计算散点的新 x,y 值。 circpos 包含每一步的数据数组。这效果很好,并按预期生成了散点图的动画 gif。然而,该函数是一个相当慢的数值计算,需要许多步骤才能产生稳定的输出,所以我宁愿先计算所有内容,然后仅对选定帧进行动画处理。所以我尝试了这个。
results = [circpos]
for h in range(61):
calculateStep()
results.append(circpos)
fig, ax = plt.subplots(figsize=(5, 5))
ax.set(xlim=(-WELLRADIUS,WELLRADIUS), ylim=(-WELLRADIUS,WELLRADIUS))
[x,y] = np.hsplit(results[0],2)
scat = ax.scatter(x.flatten(),y.flatten())
def animate(i):
scat.set_offsets(results.pop(0))
return scat,
anim = FuncAnimation(fig, animate, frames=60)
anim.save('test2.gif',writer='imagemagick')
plt.draw()
plt.show()
但是,使用此方法生成的 gif 仅包含动画的最后一帧。如果我从动画函数中打印数据,我发现从结果列表中弹出了正确的数值,但由于某种原因,gif 中只有最终值。我也尝试过使用results[i] 而不是results.pop(0) 我无法理解这种行为。
【问题讨论】:
标签: python matplotlib animation