Create Matplotlib Animations

MatplotlibMatplotlibBeginner
Practice Now

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

Introduction

In this lab, you will learn how to create an animation with Matplotlib. Specifically, you will learn how to pause and resume an animation using the Animation.pause() and Animation.resume() methods.

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`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) 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/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/animation_creation("`Animation Creation`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/keyword_arguments -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/with_statement -.-> lab-48857{{"`Create Matplotlib Animations`"}} matplotlib/importing_matplotlib -.-> lab-48857{{"`Create Matplotlib Animations`"}} matplotlib/figures_axes -.-> lab-48857{{"`Create Matplotlib Animations`"}} matplotlib/line_plots -.-> lab-48857{{"`Create Matplotlib Animations`"}} matplotlib/animation_creation -.-> lab-48857{{"`Create Matplotlib Animations`"}} matplotlib/event_handling -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/booleans -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/conditional_statements -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/tuples -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/function_definition -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/importing_modules -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/classes_objects -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/constructor -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/polymorphism -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/encapsulation -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/numerical_computing -.-> lab-48857{{"`Create Matplotlib Animations`"}} python/data_visualization -.-> lab-48857{{"`Create Matplotlib Animations`"}} end

Import Libraries

In this step, we will import the necessary libraries to create an animation with Matplotlib.

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

Define the Animation

In this step, we will define the animation that we want to create. We will create an animation that displays a normal distribution that moves to the right with each frame.

class PauseAnimation:
    def __init__(self):
        ## Create the figure and axis
        fig, ax = plt.subplots()
        ax.set_title('Click to pause/resume the animation')

        ## Create the x-axis values
        x = np.linspace(-0.1, 0.1, 1000)

        ## Start with a normal distribution
        self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5)
                   * np.exp(-x ** 2 / (4 * 2e-4 * 0.1)))

        ## Create the plot
        self.p, = ax.plot(x, self.n0)

        ## Create the animation
        self.animation = animation.FuncAnimation(
            fig, self.update, frames=200, interval=50, blit=True)

        ## Set the animation as unpaused
        self.paused = False

        ## Add a button press event to toggle pause
        fig.canvas.mpl_connect('button_press_event', self.toggle_pause)

    def toggle_pause(self, *args, **kwargs):
        ## Toggle between paused and unpaused
        if self.paused:
            self.animation.resume()
        else:
            self.animation.pause()
        self.paused = not self.paused

    def update(self, i):
        ## Update the normal distribution
        self.n0 += i / 100 % 5
        self.p.set_ydata(self.n0 % 20)
        return (self.p,)

Create the Animation Object

In this step, we will create an object of the PauseAnimation class that we defined in step 2.

pa = PauseAnimation()

Show the Animation

In this step, we will show the animation that we created in step 2.

plt.show()

Summary

In this lab, you learned how to create an animation with Matplotlib and how to pause and resume the animation using the Animation.pause() and Animation.resume() methods. You also learned how to create an interactive animation that responds to user input. With this knowledge, you can create your own custom animations and add interactivity to them.

Other Matplotlib Tutorials you may like