Matplotlib 2D and 3D Plotting

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you through creating a figure that contains both a 2D and a 3D plot using Matplotlib. The 2D plot will display a damped oscillation, while the 3D plot will display a sinusoidal wave.

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedPlottingGroup(["`Advanced Plotting`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) 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`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedPlottingGroup -.-> matplotlib/3d_plots("`3D Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") 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/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} matplotlib/figures_axes -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} matplotlib/line_plots -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} matplotlib/3d_plots -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} matplotlib/grid_config -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/booleans -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/tuples -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/function_definition -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/importing_modules -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/using_packages -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/numerical_computing -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} python/data_visualization -.-> lab-48829{{"`Matplotlib 2D and 3D Plotting`"}} end

Import Libraries

In this step, we will import the necessary libraries for this lab. We will use Matplotlib for plotting, NumPy for creating arrays, and mpl_toolkits for 3D plotting.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

Define Functions

In this step, we will define a function that generates a damped oscillation.

def f(t):
    return np.cos(2*np.pi*t) * np.exp(-t)

Create Figure

In this step, we will create a figure with two subplots. The first subplot will be a 2D plot, and the second subplot will be a 3D plot.

fig = plt.figure(figsize=plt.figaspect(2.))
fig.suptitle('A Tale of 2 Subplots')

Create 2D Plot

In this step, we will create a 2D plot of a damped oscillation.

ax1 = fig.add_subplot(2, 1, 1)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
t3 = np.arange(0.0, 2.0, 0.01)

ax1.plot(t1, f(t1), 'bo',
         t2, f(t2), 'k--', markerfacecolor='green')
ax1.grid(True)
ax1.set_ylabel('Damped oscillation')

Create 3D Plot

In this step, we will create a 3D plot of a sinusoidal wave.

ax2 = fig.add_subplot(2, 1, 2, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

surf = ax2.plot_surface(X, Y, Z, rstride=1, cstride=1,
                        linewidth=0, antialiased=False)
ax2.set_zlim(-1, 1)

Show Plot

In this step, we will display the figure.

plt.show()

Summary

In this lab, we created a figure with both a 2D and a 3D plot using Matplotlib. The 2D plot displayed a damped oscillation, while the 3D plot displayed a sinusoidal wave. We used NumPy to create arrays and mpl_toolkits for 3D plotting.

Other Python Tutorials you may like