Going through some tutorials on matplotlib animations and encountered this problem. I am using the matplotlib.animation funcanimation as follows:
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()
This generates the following output:
0 0 1 2 3 4 5
and so on. It is calling the first argument twice. How can I prevent this?
The blit keyword is an important one: this tells the animation to only re-draw the pieces of the plot which have changed. The time saved with blit=True means that the animations display much more quickly. We end with an optional save command, and then a show command to show the result.
stop() . Alternatively you may stop the animation with anim. event_source. stop() .
The PillowWriter class from matplotlib. animation is a writer that allows us to save animations we create in matplotlib . Pillow is a fork of the Python Image Library (PIL). Both PIL and Pillow come with matplotlib .
You can use an initialization function and provide it to FuncAnimation
using the init_func
argument. That way the first call will be on the init function and not the update function.
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()
This prints 0 1 2 3 ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With