Matplotlib Animation Example

2019-03-05-matplotlib-example-ii

Matplotlib Animation Tutorial

Matplotlib has an Animation class that can be used to produce moving pictures.

From my point of view, the Animation class is hard to work with because of the way it is structured. The assumption is that you are making a single scene (Axes) and changing the data displayed in those axes dynamically. This is exactly not the way a "pure" language like Racket handles animation.

I imagine there is a tradeoff for speed of animation, but I don't like the setup.

In [4]:
# Initialization
import pandas as pd
import numpy as np
import seaborn as sns
import scipy
import matplotlib.pyplot as plt
import matplotlib.animation as animation

from IPython.display import HTML
In [5]:
# Use html5 to render animations 
## required me to install ffmpeg 
from matplotlib import rc
rc('animation', html='html5')

Step by step animation

In [102]:
fig, ax = plt.subplots()
line, = ax.plot([],[])
scatter_N = 50
scatter_xs = np.random.uniform(low=-10,high=10,size=scatter_N)
scatter_ys = np.random.uniform(low=-10,high=10,size=scatter_N)
scatter = ax.scatter(scatter_xs,scatter_ys,s=16)
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
Out[102]:
(-10, 10)
In [104]:
def colorize(model,x,y):
    if x*x + y*y < model*model:
        return (1, 0, 0)
    else:
        return (0,0,1)
In [105]:
def update(model):
    t = np.linspace(0,2*np.pi,90)
    xs = model * np.cos(t)
    ys = model * np.sin(t)
    colors = [colorize(model,x,y) 
              for (x,y) in zip(scatter_xs,scatter_ys)]
    line.set_data(xs,ys)
    scatter.set_edgecolors(colors)
In [106]:
ani = animation.FuncAnimation(fig,func=update,frames=10,interval=500)
In [107]:
ani
Out[107]: