Create Animated Matplotlib Subplots

PythonPythonBeginner
Practice Now

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

Introduction

This step-by-step lab demonstrates how to create an animation with multiple subplots using Matplotlib in Python. The example shows how to animate a circle and a sine curve across two different subplots.

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/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") 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`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") 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/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") 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-48840{{"`Create Animated Matplotlib Subplots`"}} python/with_statement -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} matplotlib/importing_matplotlib -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} matplotlib/figures_axes -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} matplotlib/line_plots -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} matplotlib/animation_creation -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/variables_data_types -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/numeric_types -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/booleans -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/type_conversion -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/lists -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/tuples -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/function_definition -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/importing_modules -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/using_packages -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/data_collections -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/numerical_computing -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/data_visualization -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} python/build_in_functions -.-> lab-48840{{"`Create Animated Matplotlib Subplots`"}} end

Import Libraries

The first step is to import the required libraries, including Matplotlib, NumPy, and Matplotlib's animation module.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.patches import ConnectionPatch

Create the Figure and Subplots

The second step is to create the figure and subplots that will be used for the animation. In this example, we create two subplots side-by-side with different aspect ratios. The left subplot is a unit circle, and the right subplot is an empty plot that will be used to animate a sine curve.

fig, (axl, axr) = plt.subplots(
    ncols=2,
    sharey=True,
    figsize=(6, 2),
    gridspec_kw=dict(width_ratios=[1, 3], wspace=0),
)
axl.set_aspect(1)
axr.set_box_aspect(1 / 3)
axr.yaxis.set_visible(False)
axr.xaxis.set_ticks([0, np.pi, 2 * np.pi], ["0", r"$\pi$", r"$2\pi$"])

Draw the Circle and Initial Point

The third step is to draw the circle and initial point on the left subplot. We create an array of angles to generate the circle, and then plot the sine and cosine of each angle. We also plot a single point at the origin.

x = np.linspace(0, 2 * np.pi, 50)
axl.plot(np.cos(x), np.sin(x), "k", lw=0.3)
point, = axl.plot(0, 0, "o")

Draw the Sine Curve

The fourth step is to draw the sine curve on the right subplot. We create an array of angles, and then plot the sine of each angle. We also save the sine plot object, which we will update later in the animation.

sine, = axr.plot(x, np.sin(x))

Draw the Connection Line

The fifth step is to draw a dotted line connecting the two subplots. We create a ConnectionPatch object that connects the origin of the left subplot to the right edge of the right subplot. We also save the con patch object, which we will update later in the animation.

con = ConnectionPatch(
    (1, 0),
    (0, 0),
    "data",
    "data",
    axesA=axl,
    axesB=axr,
    color="C0",
    ls="dotted",
)
fig.add_artist(con)

Define the Animation Function

The sixth step is to define the animation function. This function will be called for each frame of the animation, and will update the position of the point on the left subplot, the position and data of the sine curve on the right subplot, and the position of the connection patch.

def animate(i):
    x = np.linspace(0, i, int(i * 25 / np.pi))
    sine.set_data(x, np.sin(x))
    x, y = np.cos(i), np.sin(i)
    point.set_data([x], [y])
    con.xy1 = x, y
    con.xy2 = i, y
    return point, sine, con

Create the Animation

The seventh step is to create the animation object using the FuncAnimation function. We pass in the figure object, the animation function, the interval between frames in milliseconds, the number of frames, and a delay before repeating the animation.

ani = animation.FuncAnimation(
    fig,
    animate,
    interval=50,
    blit=False,  ## blitting can't be used with Figure artists
    frames=x,
    repeat_delay=100,
)

Show the Animation

The final step is to show the animation using the show function of the pyplot module.

plt.show()

Summary

This step-by-step lab demonstrated how to create an animation with multiple subplots using Matplotlib in Python. The example showed how to animate a circle and a sine curve across two different subplots. The steps included importing libraries, creating the figure and subplots, drawing the circle and initial point, drawing the sine curve, drawing the connection line, defining the animation function, creating the animation object, and showing the animation.

Other Python Tutorials you may like