This notebook shows how to make animations using MoviePy and Matplotlib. Here are links to the MoviePy documentation and a short tutorial:
Let's start by importing everything we need:
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from moviepy.video.io.bindings import mplfig_to_npimage
import moviepy.editor as mpy
To create an animation we need to do two things:
In [2]:
duration = 10.0 # this is the total time
N = 500
# Make the initial plot outside the animation function
fig_mpl, ax = plt.subplots(1,figsize=(5,3), facecolor='white')
x = np.random.normal(0.0, 1.0, size=N)
y = np.random.normal(0.0, 1.0, size=N)
plt.sca(ax)
plt.xlim(-3,3)
plt.ylim(-3,3)
scat = ax.scatter(x, y)
def make_frame_mpl(t):
# t is the current time between [0,duration]
newy = y*np.cos(4.0*t/duration)
# Just update the data on each frame
# set_offset takes a Nx2 dimensional array of positions
scat.set_offsets(np.transpose(np.vstack([x, newy])))
# The mplfig_to_npimage convert the matplotlib figure to an image that
# moviepy can work with:
return mplfig_to_npimage(fig_mpl)
animation = mpy.VideoClip(make_frame_mpl, duration=duration)
"""First argument is a function that takes time. Movipy calls function and passes the current time.
Times passed is between 0 and the duration. The exact values of the time passed depends on the fps."""
Use the following call to generate and display the animation in the notebook:
In [3]:
animation.ipython_display(fps=24)
Out[3]:
Use the following to save the animation to a file that can be uploaded you YouTube:
In [4]:
animation.write_videofile("scatter_animation.mp4", fps=20)