PythonBeginner
3D Surface Plotting with Matplotlib
This tutorial is from open-source community. Access the source code
Contents
- Introduction
- Import Libraries
- Create Figure and Axes
- Create Data
- Plot the Surface
- Customize the Z Axis
- Add a Color Bar
- Summary
share
Introduction
This lab is a step-by-step tutorial on how to plot a 3D surface using Matplotlib in Python. The 3D surface is colored with the coolwarm colormap and made opaque by using "antialiased=False". The tutorial also demonstrates using the .LinearLocator
and custom formatting for the z axis tick labels.
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`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) 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/AdvancedPlottingGroup -.-> matplotlib/3d_plots("`3D Plots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") 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 python/comments -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} matplotlib/3d_plots -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/booleans -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/tuples -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/dictionaries -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/importing_modules -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/using_packages -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/numerical_computing -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} python/data_visualization -.-> lab-48973{{"`3D Surface Plotting with Matplotlib`"}} end
Import Libraries
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import cmfrom matplotlib.ticker import LinearLocator
We import the necessary libraries for the tutorial. Matplotlib is a plotting library for Python that provides an interface similar to MATLAB. Numpy is a fundamental package for scientific computing in Python.
Create Figure and Axes
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
We create a figure and axes with the subplot_kw
parameter set to "projection": "3d"
. This will create a 3D projection of the plot.
Create Data
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)
We create the data for the plot. We create the X
and Y
values as arrays with evenly spaced values from -5 to 5 in increments of 0.25. We then create a meshgrid of X
and Y
values using np.meshgrid()
. We use the meshgrid to calculate the R
values, which is the distance from the origin. We then calculate the Z
values using the sin()
function of R
.
Plot the Surface
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
We plot the surface using the plot_surface()
function. We pass in the X
, Y
, and Z
values as well as the cmap
parameter set to cm.coolwarm
to color the surface with the coolwarm colormap. We also set linewidth=0
to remove the wireframe and antialiased=False
to make the surface opaque.
Customize the Z Axis
ax.set_zlim(-1.01, 1.01)ax.zaxis.set_major_locator(LinearLocator(10))## A StrMethodFormatter is used automaticallyax.zaxis.set_major_formatter('{x:.02f}')
We customize the z axis using the set_zlim()
function to set the limits of the z axis to -1.01 to 1.01. We then use the set_major_locator()
function to set the number of ticks on the z axis to 10 using LinearLocator(10)
. Finally, we use the set_major_formatter()
function to format the z axis tick labels using a StrMethodFormatter
.
Add a Color Bar
fig.colorbar(surf, shrink=0.5, aspect=5)
We add a color bar to the plot using the colorbar()
function. We pass in the surf
object and set shrink=0.5
and aspect=5
to adjust the size of the color bar.
Summary
This tutorial demonstrated how to plot a 3D surface using Matplotlib in Python. We created a figure and axes, created the data, plotted the surface, customized the z axis, and added a color bar. Matplotlib is a powerful tool for creating visualizations in Python.
topics
Join Our Discord and Learn Together
Join Now