我想创建一个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)
但是我需要使用AFAIKAnimation
的save()
功能。那么,有可能开车Animation
而不是让我开车吗?如果可以,怎么办?
一个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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句