Skip to main content

Section 1.5 Basic Animation

In this section we will create some basic animations in Matplotlib. Static graphs convey a lot of information in one visual. The right animation can help you convey complicated information simply.

Subsection Creating a .gif in Matplotlib

Matplotlib has a module called animation with a FuncAnimation class that allows you easily make frames of a changing graph.
 4 
Animation is basically a slideshow of pictures or frames.
A class called PillowWriter allows you to grab frames and save them to a file to make gifs.
There are many ways to alter a graph over time. For these examples we will start with an empty graph and use NumPy’s append to add points one at a time to our graph.

You Try 1.31.

  • Play with various graph features and customizations.
  • Add a title and labels to your graph.

You Try 1.32.

  • Change the dpi and see how the .gif is affected.
  • Change the frames per second and see how the .gif is affected.
Here is an example animating two curves on the same graph.

Subsection Creating an interactive slider

This second example uses interact to create a slider to plot one point at a time. We will need to create two user defined (computer science) functions: one that increments through the input points for the slider and another that plots the graph for just those input points.

You Try 1.33.

  • Play with various graph features and customizations.
  • Change the number of frames to see how the interactive is affected.
Hint.
Try aligning and misaligning the number of frames and the number of inputs plotted.
Here is the same interactive for projectile motion.

Subsection Student Showcase

Former students gave us permission to share some of their work as well.

Example 1.34. Anonymous (Spring 2024).

Example 1.35. Luke Clark (Spring 2024).

Example 1.36. Ben Cantarero (Spring 2024).

Matplotlib allows you to not only graph, but make your graphs interactive. You can use interact to create interactive elements. The animation module can be used to animate your graphs. Hopefully this is enough to get you started.

Summary.

  • The FuncAnimation class can be used to animate your graphs and PillowWriter saves those frames into a gif.
  • We can use interact to create a slider element and create two user defined functions: one that takes the slider information to create points and another that makes graphs for just those points.

Exercises Exercises

1.

Animate a 3D graph.

2.

Showcase your skills from so far in the term to create an animated graph in Matplotlib for any other class (and using one feature we haven’t learned in class).

3.

What graph do you want to animate? Create it!