Creating Animated Images with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create an animated image using precomputed lists of images. We will be using the Matplotlib library in Python to create the animation. The purpose of this lab is to demonstrate the process of creating an animated image and to provide a basic understanding of how it works.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/animation_creation("`Animation Creation`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} matplotlib/heatmaps -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} matplotlib/animation_creation -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/booleans -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/conditional_statements -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/for_loops -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/lists -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/tuples -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/function_definition -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/importing_modules -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/numerical_computing -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/data_visualization -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} python/build_in_functions -.-> lab-48695{{"`Creating Animated Images with Matplotlib`"}} end

Import Libraries

To start, we need to import the libraries that we will be using. We will be using the Matplotlib library to create the animation and the Numpy library to generate the data for the animation.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

Create the Figure and Axes Objects

Next, we need to create the figure and axes objects that we will be using to create the animation. We will be using the subplots method to create these objects.

fig, ax = plt.subplots()

Define the Function

We now need to define the function that we will be using to generate the data for the animation. In this example, we will be using the sine and cosine functions to generate the data.

def f(x, y):
    return np.sin(x) + np.cos(y)

Generate the Data

We will be using the linspace method from the Numpy library to generate the data for the animation. We will be generating two sets of data, x and y, and then reshaping the y data to create a two-dimensional array.

x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)

Create the Animation Frames

We will now create the frames for the animation. We will be using a for loop to generate 60 frames. In each iteration of the loop, we will be updating the x and y data and then creating a new image object using the imshow method. We will then append the image object to the ims list.

ims = []
for i in range(60):
    x += np.pi / 15
    y += np.pi / 30
    im = ax.imshow(f(x, y), animated=True)
    if i == 0:
        ax.imshow(f(x, y))  ## show an initial one first
    ims.append([im])

Create the Animation

We will now create the animation using the ArtistAnimation method. We will be passing in the figure object, the ims list, the interval between frames, and the repeat delay.

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)

Display the Animation

Finally, we will use the show method to display the animation.

plt.show()

Summary

In this lab, we learned how to create an animated image using precomputed lists of images. We used the Matplotlib library in Python to create the animation and the Numpy library to generate the data for the animation. We created the figure and axes objects, defined the function, generated the data, created the animation frames, and created the animation. We then displayed the animation using the show method. This lab provided a basic understanding of how to create an animated image and demonstrated the process of doing so.

Other Python Tutorials you may like