Inline Animations

Matplotlib animations can also be run inline in HTML files as well as saved to files for download. The follwing requires installation of the libraries:

  • ffmpeg, in my case installed with Conda via conda install -c menpo ffmpeg, and
  • imagemagick, in my case installed with Conda via conda install -c conda-forge imagemagick
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import animation, rcParams
from IPython.display import HTML, Image

rcParams['animation.html']= 'html5'
n = 500
x = np.random.randn(n)
print(x[:5])
[ 0.57547228 -0.03268633 -0.82129656  1.02268911 -0.59361437]
def animate(curr):
    plt.cla()
    bins = np.arange(-4, 4, 0.5)
    
    plt.hist(x[:curr], 
             bins=bins)
    
    plt.axis([-4,4,0,110])
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value');
    
    title = 'Sampling the Normal Distribution - n = {}'.format(curr)
    plt.gca().set_title(title);
fig = plt.figure()
a = animation.FuncAnimation(fig, 
                            animate, 
                            frames=n,
                            interval=20)
a

png