Ramon Martinez Ramon Martinez - 3 months ago 33
Python Question

matplotlib animation duration

the code here below shows and saves an animation of random matrices in succession. My question is how can I adjust the duration of the animation that I save. The only parameters that I have here fps, and dpi control first how many seconds a frame remains and the second controls the quality of the image. What I want is to actually control the number of frames that are going to be saved in terms of the matrices the number of them that are actually stored.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

N = 5

A = np.random.rand(N,N)
im = plt.imshow(A)

def updatefig(*args):
im.set_array(np.random.rand(N,N))
return im,

ani = animation.FuncAnimation(fig, updatefig, interval=200, blit=True)

ani.save('try_animation.mp4', fps=10, dpi=80) #Frame per second controls speed, dpi controls the quality
plt.show()


I am wonderinf if I should add more parameters. I tried to look for the appropriate one in the class documentation in matplotlib but I was unsuccessful:

http://matplotlib.org/api/animation_api.html#module-matplotlib.animation

Answer

The documentation reveals that FuncAnimation accepts an argument frames, which controls the total number of frames played. Your code could thus read

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

N = 5

A = np.random.rand(N,N)
im = plt.imshow(A)

def updatefig(*args):
    im.set_array(np.random.rand(N,N))
    return im,

ani = animation.FuncAnimation(fig, updatefig, frames=10, interval=200, blit=True) 

ani.save('try_animation.mp4', fps=10, dpi=80) #Frame per second controls speed, dpi       controls the quality 
plt.show()

to play 10 frames.

Comments