How can I specify the duration when saving a matplotlib animation to a file? Usually it would be given by the frame
argument of animation.FuncAnimation()
, but not when using a generator to create the frames of the animation. E.g. using this example
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def simData():
t_max = 10.0
dt = 0.05
x = 0.0
t = 0.0
while t < t_max:
x = np.sin(np.pi*t)
t = t + dt
yield x, t
def simPoints(simData):
x, t = simData[0], simData[1]
time_text.set_text(time_template%(t))
line.set_data(t, x)
return line, time_text
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'bo', ms=10)
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)
time_template = 'Time = %.1f s' # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
ani = animation.FuncAnimation(fig, simPoints, simData)
#plt.show()
ani.save('animation.mp4', writer="avconv", codec="libx264")
creates a 20 sec video displaying approx. five sec of "simulation time", half of the frames the generator would generate when displaying it with plt.show()
.