【问题标题】:Matplotlib animation; animate in push mode, not with a call back functionMatplotlib 动画;以推送模式进行动画处理,而不是使用回调函数
【发布时间】:2017-05-28 20:32:03
【问题描述】:

我想创建一个 matplotlib 动画,但我不想让 matplotlib 给我打电话,我想打电话给 matplotlib。例如我想这样做:

from random import random
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def update(frame):
    plt.scatter(random(),random())

fig, ax = plt.subplots()
ani = FuncAnimation(fig, update, interval=340, repeat=True)
ani.save("my.mov", "avconv")

像这样:

def update():
    plt.scatter(random(),random())

fig, ax = plt.subplots()
ani = MadeUpSubClassPassiveAnimation(fig)

while True:
  update()
  ani.update()
  # do other stuff ...

ani.save("my.mov", "avconv") 

我意识到我可以像这样驱动现场情节:

def update():
  plt.scatter(x, y)
  plt.pause(0.01)

fig, ax = plt.subplots()
plt.ion()

while True:
  update()
  time.sleep(1)

但是 AFAIK 我需要使用 Animation 来实现 save() 功能。那么,是否可以驾驶Animation 而不是让它驾驶我?如果有怎么办?

【问题讨论】:

  • 对于使用循环的示例,请参见例如this question,但周围还有数百个其他示例。但是,这听起来像是典型的XYproblem。能否请您具体说明这样做的目的是什么?
  • 这不是 XY 问题。为什么?因为就代码结构而言,它更有意义。我希望 matplotlib 视图只是另一个输出处理程序。就像模型/视图模式中的视图。我的模型做了一些事情,然后通知处理程序,其中一个可能是也可能不是 matplotlib 动画。
  • 看,我们正在进行典型的 XY 问题讨论。 ;-) while 循环不会通知任何人任何事情。您能否以一种清楚您需要什么的方式写下这个问题?
  • 不,对不起,我不能。上面写的问题的形式简洁地达到了我想要的核心,没有任何分心/臃肿。我在 SO 上与许多人进行过讨论,我对如何写问题的看法没有改变;)。
  • @ImportanceOfBeingErnest AFAICT 我的问题不是这些问题的重复,因为这些问题不使用动画。我已经更新了我的问题以尝试更好地解释。

标签: python animation matplotlib


【解决方案1】:

Animation 在保存时运行。这意味着动画在运行两次(一次用于保存,一次用于显示)时需要可重现地给出相同的结果。换句话说,动画需要根据连续帧来定义。有了这个要求,任何动画都可以使用函数 (FuncAnimation) 或帧列表 (ArtistAnimation) 上的回调来构造。

问题中的示例可以使用ArtistAnimation 来完成(为了使保存的动画和显示的动画分别没有不同的随机数):

import matplotlib.pyplot as plt
import matplotlib.animation
from random import random

def update(frame):
    sc = ax.scatter(random(),random())
    return [sc]

fig, ax = plt.subplots()

artists = []

for i in range(10):
    sc = update(i)
    artists.append(sc)

# If you want previous plots to be present in all frames, add
#artists = [[j[0] for j in artists[:i+1]] for i in range(len(artists))]

ani = matplotlib.animation.ArtistAnimation(fig,artists,interval=100)
ani.save(__file__+".gif", writer="imagemagick") 
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多