浏览matplotlib动画的一些教程并遇到此问题。我使用matplotlib.animation funcanimation如下:
import matplotlib.animation as animation
import numpy as np
from pylab import *
def ani_frame():
fig = plt.figure()
ax = fig.add_subplot(111)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
im = ax.imshow(rand(7, 7), cmap='gray', interpolation='nearest')
tight_layout()
def update_img(n):
print(n)
tmp = rand(7, 7)
im.set_data(tmp)
return im
ani = animation.FuncAnimation(fig, update_img, np.arange(0, 20, 1), interval=200)
writer = animation.writers['ffmpeg'](fps=5)
ani.save('demo.mp4', writer=writer)
return ani
ani_frame()
这会生成以下输出:
0 0 1 2 3 4 5
等等。它两次调用第一个参数。我该如何防止这种情况?
答案 0 :(得分:3)
您可以使用初始化函数,并使用FuncAnimation
参数将其提供给init_func
。这样第一次调用将在init函数上,而不是更新函数。
import matplotlib.animation as animation
import numpy as np
from pylab import *
def ani_frame():
fig = plt.figure()
ax = fig.add_subplot(111)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
im = ax.imshow(rand(7, 7), cmap='gray', interpolation='nearest')
tight_layout()
def init():
#do nothing
pass
def update_img(n):
print(n)
tmp = rand(7, 7)
im.set_data(tmp)
ani = animation.FuncAnimation(fig, update_img, np.arange(0, 20, 1),
init_func=init, interval=200)
writer = animation.writers['ffmpeg'](fps=5)
ani.save('demo.mp4', writer=writer)
return ani
ani_frame()
这打印0 1 2 3 ....