How to save a matplotlib.pause animation to video?

Question:

I have an animation created with plt.pause as below…

import matplotlib.pyplot as plt

for i in range(10):
    plt.scatter(0, i)
    plt.pause(0.01)

plt.show()

How can I save this as a video file, e.g. a .mp4 file?

Asked By: SamTheProgrammer

||

Answers:

First, I have to redefine the plotting as a function with the plotted point given by a frame i. plt.pause() can be replaced by matplotlib.animate. Finally, I used a package suggested here to get the conversion to .mp4 format. You will need to install MoviePy:

pip install MoviePy

and then I just animate the function with matplotlib.animate into a .gif format before sending it to MoviePy. You’ll need to figure out what directory you want this all to happen in. I’m just using the current working directory.

Here is the code:

import matplotlib.pyplot as plt
import matplotlib.animation as ani
import os
import moviepy.editor as mp


frames=20
fig = plt.figure()
ax = plt.gca()
def scatter_ani(i=int):
    plt.scatter(0, i)

anim = ani.FuncAnimation(fig, scatter_ani, frames=frames, interval=50)
anim.save("test.gif")

clip = mp.VideoFileClip(path+name)
clip.write_videofile("test.mp4")

The gif is then

Result

To tweak the length of the animation, check out the docs for matplotlib.animate. For example, if you want to clear all of the previous data-points and show only the dot moving up, then you need to clear the axes in the function, and bound the y-axis so you see the motion, i.e.

def scatter_ani(i=int):
    ax.clear()
    ax.set_ylim(0, frames+1)
    plt.scatter(0, i)

to get:

result

Answered By: t.o.