3D Surface Plotting with Matplotlib (2024)

PythonBeginner

3D Surface Plotting with Matplotlib (2)

3D Surface Plotting with Matplotlib

Practice Now

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

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

LinuxDockerKubernetesGitJavaHadoop
Create Polar Plots with MatplotlibMatplotlib is a Python library used for creating static, animated, and interactive visualizations in Python. One of the key features of Matplotlib is its ability to create 2D and 3D plots of all types and styles, including scatter plots, line plots, and bar charts. In this lab, you will learn how to create a polar curve in a rectangular box using Matplotlib.Formatting Currency Plots with MatplotlibIn this lab, we will learn how to use Matplotlib to format the y-axis labels of a plot to display dollar signs. This is particularly useful when working with financial data or any data that requires currency formatting.Creating Matplotlib Timeline VisualizationsIn this lab, you will learn how to create a simple timeline using Matplotlib release dates. A timeline is a graphical representation of a sequence of events in chronological order. Timelines can be created with a collection of dates and text. In this example, we will show how to create a simple timeline using the dates for recent releases of Matplotlib.

Join Our Discord and Learn Together

Join Now
3D Surface Plotting with Matplotlib (2024)
Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 5888

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.