【问题标题】:Matplotlib function animation not animating for pre-calculated dataMatplotlib 函数动画不为预先计算的数据设置动画
【发布时间】: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


    【解决方案1】:

    看来我解决了我自己的问题。当我将全局数组 circpos 的每次迭代添加到结果列表时,当然是浅拷贝。这意味着它只是对原始 circpos 数组的引用。因此,我最终得到一个列表,其中包含对同一对象的引用。打印出来的只是我误解了我在看什么。 相反,我现在将 circpos.copy() 添加到我的列表中,以便在每个步骤中获取数组的新副本。 在我意识到之前,这已经让我在 Python 中绊倒了。还在学习!

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2018-08-10
      相关资源
      最近更新 更多