3

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().

Community
  • 1
  • 1
sitic
  • 539
  • 4
  • 13

1 Answers1

6

You are missing the save_count keyword on FuncAnimation. If you pass it a generator, then you may pass the number of frames to save:

ani = animation.FuncAnimation(fig, simPoints, simData, save_count=200)

The iteration seems to go on until either the generator is exhausted or the save_count is reached. The default value is 100 even though it does not seem to be documented very clearly outside of the source code.

DrV
  • 22,637
  • 7
  • 60
  • 72
  • Thank you for this answer. To me it seems a little ridiculous to have to specify this rather than just exhausting the generator. Or am I doing something strange by constructing my own generator that produces a sequence of tuples that tell the animate function what to do? – KeithWM Jan 05 '17 at 14:50