Matplotlib AVI / MP4 movie

Matplotlib on any platform can use FFmpeg, Avconv or Mencoder to directly write lossy or lossless compressed movies created from sequences of plots.

Instead of creating hundreds of PNGs, or skipping plots and missing details, Matplotlib movies of a large sequence of plots is highly effective for many processes that evolve across time and/or space.

Alternatively, convert a stack of PNGs to AVI. It’s simpler and often faster and more robust to use Matplotlib.animation.

Lossy

Quality: the default auto bitrate makes excessively compressed, blocky movies. Override the default auto-bitrate with the following snippet:

import matplotlib.animation as anim

Writer = anim.writers['ffmpeg']
writer = Writer(fps=15, codec='mpeg4', bitrate=1e6)
#
with writer.saving(fg, fn,100):
    # code to plot/update figure
    writer.grab_frame(facecolor='k')

Lossless

In matplotlib_writeavi.py, just four added lines of code do the AVI writing. First line tells Matplotlib to use FFmpeg. Second line tells Matplotlib to make a lossless FFV1 video at 15 frames/sec. One can optionally use codec='mpeg4', but lossy encoding can wash out details of plots. Third line says to use 100 DPI (smaller DPI–smaller file and movie size).

import matplotlib.animation as anim

#...

Writer = anim.writers['ffmpeg']
writer = Writer(fps=15, codec='ffv1')
# ...
with writer.saving(fg, fn, 100):
# ...
   writer.grab_frame(facecolor='k')

Troubleshooting

For problems playing back the .avi file, try omitting the codec='ffv1' parameter.

Minimum AVI frame rate: less than 3 fps can invoke bugs on VLC. VLC has trouble with slow frame rate video from any source.