Matplotlib animation example

This example notebook shows one possible way to make an animation using Matplotlib in a Jupyter notebook.

Feel free to use some or all of this code in your projects!


In [ ]:
#First thing we need to do is import pyplot and numpy
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

In [ ]:
#Next we are going to import some specific libraries we will use to get the animation to work cleanly
from IPython.display import display, clear_output
import time

Create function to show neighborhood plots

Next I will create a function that takes an array as an input and generates a grid. We have chosen a value of zero (0) to represent an empty cell, a one (1) to represent a square and a (2) to represent a triangle.


In [ ]:
# function plotgrid() takes in a 2D array and uses pyplot to make a plot.
# this function returns no values!

def plotgrid(myarray):
    
    # first create two vectors based on the x and y sizes of the grid
    x_range = np.linspace(0, myarray.shape[0], myarray.shape[0]) 
    y_range = np.linspace(0, myarray.shape[0], myarray.shape[0])
    
    # use the numpy meshgrid function to create two matrices 
    # of the same size as myarray with x and y indexes
    x_indexes, y_indexes = np.meshgrid(x_range, y_range)
    
    # make a list of all the x and y indexes that are either squares or triangles.
    # the notation below is relatively new to us; it means that when myarray==(value),
    # only record those values.
    sq_x = x_indexes[myarray == 1]; 
    sq_y = y_indexes[myarray == 1]; 
    tr_x = x_indexes[myarray == 2]; 
    tr_y = y_indexes[myarray == 2]; 
    
    # plot the squares and triangles.  make the size of the polygons 
    # larger than the default so they're easy to see!
    plt.plot(sq_x,sq_y, 'bs',markersize=20)   
    plt.plot(tr_x,tr_y, '^g',markersize=20)  
    
    #Set the x and y limits to include half a space overlap so we don't cut off the shapes
    plt.ylim([-0.5,20.5]) 
    plt.xlim([-0.5,20.5])

ALWAYS Test

Now test the function by creating a random neighborhood array with either zeros, ones, or twos


In [ ]:
# Generate a random grid of points (note this does not guarantee 1/3, 1/3 and 1/3 like in the homework)
neighborhood_array = np.random.random_integers(0,2,size=[20,20]) 
plt.figure(figsize=(10,10)) #Do you know what this line is doing? Try commenting this out to see how the figure looks?
plotgrid(neighborhood_array)

Moving Animation

Looks good so far! Finally, we are going to animate the loop using a dynamic display trick. What we will do is create a figure and keep clearing the figure and overwriting it with a new figure. In this example we just keep making a new random neighborhood 10 times while pausing a half second between each neighbornood; if you were to do this in your own homework assignment you would probably do something a bit different.


In [ ]:
# Create a figure
fig = plt.figure(figsize=(10,10))

# Run animation for 10 iterations
for i in range(10): 
    # Generate the random neighborhood 
    myarray = np.random.random_integers(0,2,size=[20,20])
    
    # Put display code here
    plotgrid(myarray)   
    
    # Animaiton part (dosn't change)
    time.sleep(0.5)         # Sleep for half a second to slow down the animation
    clear_output(wait=True) # Clear output for dynamic display
    display(fig)            # Reset display
    fig.clear()             # Prevent overlapping and layered plots

plt.close()                 # Close dynamic display

That's it! You can see the animation again by just re-running the above cell. Have fun making your own animations using Jupyter Notebooks!