Creating Animated Plot Videos using Matplotlib

Aug. 24, 2018, 5:20 p.m.

It can be very useful to create animations of plots in order to visualize how values change over time. Below is a way to create video file using matplotlib.

NOTES :

Version using writer context manager

This method uses the writer.saving context manager, which handles cleaning up and properly closing the video filestream in the event that an error occurs in the loop.

import numpy as np
import matplotlib
# matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Settings
video_file = "myvid.mp4"
clear_frames = True     # Should it clear the figure between each frame?
fps = 15

# Output video writer
FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!')
writer = FFMpegWriter(fps=fps, metadata=metadata)

fig = plt.figure()
x = np.arange(0,10,0.1)
with writer.saving(fig, video_file, 100):
    for i in np.arange(1, 10, 0.1):
        y = np.sin(x+i)
        if clear_frames:
            fig.clear()
        ax, = plt.plot(x, y, 'r-', linestyle="solid", linewidth=1)
        writer.grab_frame()

Running the above code we get:

Setting the clear frames to False we get:

Version not using writer context manager

import numpy as np
import matplotlib
# matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Settings
video_file = "myvid.mp4"
clear_frames = True     # Should it clear the figure between each frame?
fps = 15

# Output video writer
FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!')
writer = FFMpegWriter(fps=fps, metadata=metadata)

fig = plt.figure()
writer.setup(fig, outfile=video_file, dpi=None)
x = np.arange(0,10,0.1)
for i in np.arange(1, 10, 0.1):
    y = np.sin(x+i)
    if clear_frames:
        fig.clear()
    ax, = plt.plot(x, y, 'r-', linestyle="solid", linewidth=1)
    writer.grab_frame()
writer.finish()
# writer.cleanup()

Comments

Note you can comment without any login by:

  1. Typing your comment
  2. Selecting "sign up with Disqus"
  3. Then checking "I'd rather post as a guest"