Matplotlib 3D Plot Animation

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you on how to create a simple animation of a rotating 3D plot about all three axes using Matplotlib. We will use a sample dataset to create a basic wireframe, set axis labels, and rotate the axes.

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/AdvancedPlottingGroup(["`Advanced Plotting`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/AdvancedPlottingGroup -.-> matplotlib/3d_plots("`3D Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/animation_creation("`Animation Creation`") 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/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} matplotlib/importing_matplotlib -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} matplotlib/figures_axes -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} matplotlib/3d_plots -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} matplotlib/titles_labels -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} matplotlib/animation_creation -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/conditional_statements -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/for_loops -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/lists -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/tuples -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/importing_modules -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/using_packages -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/data_visualization -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} python/build_in_functions -.-> lab-48906{{"`Matplotlib 3D Plot Animation`"}} end

Import Libraries and Dataset

First, we need to import the necessary libraries and dataset. In this example, we will use the matplotlib and mpl_toolkits.mplot3d libraries to create the 3D plot, and the axes3d.get_test_data() function to generate a sample dataset.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

## Generate sample dataset
X, Y, Z = axes3d.get_test_data(0.05)

Create a 3D Plot

Next, we will create a 3D plot using the plt.figure() and fig.add_subplot() functions. We will also use the ax.plot_wireframe() function to plot the dataset as a wireframe.

## Create 3D plot
fig = plt.figure()
ax = fig.add_subplot(projection='3d')

## Plot wireframe
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

Set Axis Labels

We will now set the axis labels for the 3D plot using the ax.set_xlabel(), ax.set_ylabel(), and ax.set_zlabel() functions.

## Set axis labels
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

Rotate the Axes and Update the Plot

Finally, we will rotate the axes and update the plot using a for loop that cycles through a full rotation of elevation, then azimuth, roll, and all. We will use the ax.view_init() function to update the axis view and title, and the plt.title(), plt.draw(), and plt.pause() functions to display the animation.

## Rotate the axes and update the plot
for angle in range(0, 360*4 + 1):
    ## Normalize the angle to the range [-180, 180] for display
    angle_norm = (angle + 180) % 360 - 180

    ## Cycle through a full rotation of elevation, then azimuth, roll, and all
    elev = azim = roll = 0
    if angle <= 360:
        elev = angle_norm
    elif angle <= 360*2:
        azim = angle_norm
    elif angle <= 360*3:
        roll = angle_norm
    else:
        elev = azim = roll = angle_norm

    ## Update the axis view and title
    ax.view_init(elev, azim, roll)
    plt.title('Elevation: %d°, Azimuth: %d°, Roll: %d°' % (elev, azim, roll))

    ## Display animation
    plt.draw()
    plt.pause(.001)

Summary

In this lab, we learned how to create a simple animation of a rotating 3D plot about all three axes using Matplotlib. We used a sample dataset to create a basic wireframe, set axis labels, and rotated the axes. We also learned how to use the ax.view_init(), plt.title(), plt.draw(), and plt.pause() functions to update the plot and display the animation.

Other Python Tutorials you may like