Basic animations with Matplotlib in Python

I want to provide a brief example on how you can create plot-based animations with Matplotlib in Python. Below Python code implements a simple exponential growth animation. Documentation is added directly to the code in the form of comments.

# setting jupyter notebook to display animation
%matplotlib notebook

# importing relevant modules & packages
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# creating x and y coordinate data lists
x = []
y = []

# set matplotlib figure size
plt.figure(figsize=(5,5))

# create subplot figure and axes handlers
fig, ax = plt.subplots()

# set axis limits, for x and y axis
ax.set_xlim(0,100)
ax.set_ylim(0,1.1**100)

# set axis labels
ax.set_xlabel("time", 
              fontsize = 14)
ax.set_ylabel("observation value", 
              fontsize = 14)

# set title
ax.set_title("Animating exponential growth with Matplotlib",
            fontsize = 14)

# create a line plot reference; 
# at the same time set line color etc.
line, = ax.plot(0,0, 
                color='red', 
                linestyle='-', 
                linewidth=2, 
                markersize=2)

# define an animation function
def frameAnimation(i):
    # set x and y values
    x.append(i)
    y.append(1.10**i)
    # update line plot
    line.set_xdata(x)
    line.set_ydata(y)
    # return line object
    return line,

# create animation object
animation = FuncAnimation(fig, # the figure to assign animation too
                          func = frameAnimation, # the frame rendering function
                          frames = np.arange(0,100,0.1), # the steps and amount of frames
                         interval = 10) # invertals is the time per frame, in ms

# show animation
plt.show()

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta