The Wayback Machine - https://web.archive.org/web/20240725000137/https://www.geeksforgeeks.org/3d-surface-plotting-in-python-using-matplotlib/
Open In App

3D Surface plotting in Python using Matplotlib

Last Updated : 22 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

A Surface Plot is a representation of three-dimensional dataset. It describes a functional relationship between two independent variables X and Z and a designated dependent variable Y, rather than showing the individual data points. It is a companion plot of the contour plot. It is similar to the wireframe plot, but each face of the wireframe is a filled polygon. This helps to create the topology of the surface which is being visualized.
 

Creating 3D surface Plot

The axes3d present in Matplotlib’s mpl_toolkits.mplot3d toolkit provides the necessary functions used to create 3D surface plots.Surface plots are created by using ax.plot_surface() function.
Syntax: 

ax.plot_surface(X, Y, Z)

where X and Y are 2D array of points of x and y while Z is 2D array of heights.Some more attributes of ax.plot_surface() function are listed below:
 

Attribute Description
X, Y, Z 2D arrays of data values
cstride array of column stride(step size)
rstride array of row stride(step size)
ccount number of columns to be used, default is 50
rcount number of row to be used, default is 50
color color of the surface
cmap colormap for the surface
norm instance to normalize values of color map
vmin minimum value of map
vmax maximum value of map
facecolors face color of individual surface
shade shades the face color

Example: Let’s create a 3D surface by using the above function 

Python3




# Import libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
 
# Creating dataset
x = np.outer(np.linspace(-3, 3, 32), np.ones(32))
y = x.copy().T # transpose
z = (np.sin(x **2) + np.cos(y **2) )
 
# Creating figure
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')
 
# Creating plot
ax.plot_surface(x, y, z)
 
# show plot
plt.show()


Output: 

Image

 

Gradient surface Plot

Gradient surface plot is a combination of 3D surface plot with a 2D contour plot. In this plot the 3D surface is colored like 2D contour plot. The parts which are high on the surface contains different color than the parts which are low at the surface.
Syntax:

surf = ax.plot_surface(X, Y, Z, cmap=, linewidth=0, antialiased=False)

The attribute cmap= sets the color of the surface. A color bar can also be added by calling fig.colorbar. The code below create a gradient surface plot:
Example:

Python3




# Import libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Creating dataset
x = np.outer(np.linspace(-3, 3, 32), np.ones(32))
y = x.copy().T # transpose
z = (np.sin(x **2) + np.cos(y **2) )
 
# Creating figure
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')
 
# Creating color map
my_cmap = plt.get_cmap('hot')
 
# Creating plot
surf = ax.plot_surface(x, y, z,
                       cmap = my_cmap,
                       edgecolor ='none')
 
fig.colorbar(surf, ax = ax,
             shrink = 0.5, aspect = 5)
 
ax.set_title('Surface plot')
 
# show plot
plt.show()


Output: 

Image

 

3D surface Plot having 2D contour plot projections

3D surface plots plotted with Matplotlib can be projected on 2D surfaces. The code below creates a 3D plots and visualizes its projection on 2D contour plot:
Example: 

Python3




# Import libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Creating dataset
x = np.outer(np.linspace(-3, 3, 32), np.ones(32))
y = x.copy().T # transpose
z = (np.sin(x **2) + np.cos(y **2) )
 
# Creating figure
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')
 
# Creating color map
my_cmap = plt.get_cmap('hot')
 
# Creating plot
surf = ax.plot_surface(x, y, z,
                       rstride = 8,
                       cstride = 8,
                       alpha = 0.8,
                       cmap = my_cmap)
cset = ax.contourf(x, y, z,
                   zdir ='z',
                   offset = np.min(z),
                   cmap = my_cmap)
cset = ax.contourf(x, y, z,
                   zdir ='x',
                   offset =-5,
                   cmap = my_cmap)
cset = ax.contourf(x, y, z,
                   zdir ='y',
                   offset = 5,
                   cmap = my_cmap)
fig.colorbar(surf, ax = ax,
             shrink = 0.5,
             aspect = 5)
 
# Adding labels
ax.set_xlabel('X-axis')
ax.set_xlim(-5, 5)
ax.set_ylabel('Y-axis')
ax.set_ylim(-5, 5)
ax.set_zlabel('Z-axis')
ax.set_zlim(np.min(z), np.max(z))
ax.set_title('3D surface having 2D contour plot projections')
 
# show plot
plt.show()


Output: 

Image



Previous Article
Next Article

Similar Reads

3D Wireframe plotting in Python using Matplotlib
To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: C/C++ Code # importing modules from
1 min read
Python | Matplotlib Graph plotting using object oriented API
In object-oriented API, first, we create a canvas on which we have to plot the graph and then we plot the graph. Many people prefer object-oriented API because it is easy to use as compared to functional API. Let's try to understand this with some examples. Example #1: # importing matplotlib library import matplotlib.pyplot as plt # x axis values x
2 min read
3D Contour Plotting in Python using Matplotlib
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look at a 3d contour diagram of a 3d cosine function. Th
2 min read
3D Scatter Plotting in Python using Matplotlib
A 3D Scatter Plot is a mathematical diagram, the most basic version of three-dimensional plotting used to display the properties of data as three variables of a dataset using the cartesian coordinates.To create a 3D Scatter plot, Matplotlib's mplot3d toolkit is used to enable three dimensional plotting.Generally 3D scatter plot is created by using
2 min read
Plotting cross-spectral density in Python using Matplotlib
Matplotlib is a comprehensive library consisting of modules that are used for Data Visualization just like MATLAB. Pyplot is a further module which makes functions and methods executable. Plotting Cross-Spectral Density The cross-spectral density compares two signals, each from different source taking into account both amplitude and phase differenc
2 min read
Plotting multiple bar charts using Matplotlib in Python
A multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many customizations such as Multiple bar plots, stacked bar plots, horizontal bar charts. Multiple bar charts are generally used for comparing different entities. In this article, plotting multiple bar charts are discussed. Example 1: Simple multiple bar chart In
4 min read
Plotting a Spectrogram using Python and Matplotlib
Prerequisites: Matplotlib A spectrogram can be defined as the visual representation of frequencies against time which shows the signal strength at a particular time. In simple words, a spectrogram is nothing but a picture of sound. It is also called voiceprint or voice grams. A spectrogram is shown using many colors which indicates the signal stren
3 min read
Plotting Sine and Cosine Graph using Matplotlib in Python
Data visualization and Plotting is an essential skill that allows us to spot trends in data and outliers. With the help of plots, we can easily discover and present useful information about the data. In this article, we are going to plot a sine and cosine graph using Matplotlib in Python. Matplotlib is a Python library for data visualization and pl
4 min read
Three-dimensional Plotting in Python using Matplotlib
3D plots are very important tools for visualizing data that have three dimensions such as data that have two dependent and one independent variable. By plotting data in 3d plots we can get a deeper understanding of data that have three variables. We can use various matplotlib library functions to plot 3D plots. Example Of Three-dimensional Plotting
6 min read
Plotting Histogram in Python using Matplotlib
Histograms are a fundamental tool in data visualization, providing a graphical representation of the distribution of data. They are particularly useful for exploring continuous data, such as numerical measurements or sensor readings. This article will guide you through the process of Plot Histogram in Python using Matplotlib, covering the essential
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg