create 3d surface plot in python

How to plot a 3D surface plot in Python?

In this tutorial, we’ll try to understand how to plot a 3D surface plot in python.

What is a surface plot?

A surface plot shows a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). The plot is a companion plot to the contour plot. A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon.

We can plot a 3D surface plot using the matplotlib Axes.plot_surface() method.

Using the matpltolib.Axes.plot_surface() method

We can plot a 3D surface plot using the matplotlib.Axes.plot_surface() method. Note that to create (any) 3d plot in matplotlib, you need to pass projection='3d' when creating the plot’s axes object. This way matplotlib knows that we’re creating a 3D plot. Once you have the axes object, use the plot_surface() method to get the relevant 3d surface plot.

Basic Syntax:

Axes.plot_surface(X, Y, Z, *, norm=None, vmin=None, vmax=None,lightsource=None, **kwargs)

Parameters:

  • X, Y, Z: Data values
  • rcount, ccount: Maximum number of samples used in each direction. If the input data is larger, it will be downsampled (by slicing) to these numbers of points. Defaults to 50.

For more details about the parameters refer this.

Now let us understand the usage of the above method with some examples.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Example 1

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T
z = np.cos(x ** 2 + y ** 2)

#generating a figure and a 3D axes
fig = plt.figure()
ax = plt.axes(projection='3d')

#plotting the 3D surface plot
ax.plot_surface(x, y, z)
plt.show()

Output:

the resulting 3d surface plot

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using axes.plot_surface method.

Example 2

You can customize the surface plot with additional parameters to the Axes.surface_plot() function. For example, use a different color map, change the edge color, etc.

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T
z = np.cos(x ** 2 + y ** 2)

#generating a figure and a 3D axes
fig = plt.figure()
ax = plt.axes(projection='3d')

#plotting the 3D surface plot
ax.plot_surface(x, y, z,cmap='viridis', edgecolor='none')
plt.show()

Output:

the resulting 3d surface plot with custom color map

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using axes.plot_surface method with customizations.

Example 3

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
r = np.linspace(0, 6, 20)
theta = np.linspace(-0.9 * np.pi, 0.8 * np.pi, 40)
r, theta = np.meshgrid(r, theta)

x= r * np.sin(theta)
y = r * np.cos(theta)

def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

z = f(x, y)

#generating a figure and a 3D axes
fig = plt.figure()
ax = plt.axes(projection='3d')

#plotting the 3D surface plot
ax.plot_surface(x, y, z,cmap='viridis',rstride=1, cstride=1, edgecolor='none')
plt.show()

Output:

the resulting 3d surface plot

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using the axes.plot_surface method with customizations.

Example 4

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
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) )

#generating a figure and a 3D axes
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

#plotting the 3D surface plot
ax.plot_surface(x, y, z)
plt.show()

Output:

the resulting 3d surface plot

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using axes.plot_surface method with customizations.

Example 5

Gradient surface plot.

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
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) )

#generating a figure and a 3D axes
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

#plotting the 3D surface plot
surf = ax.plot_surface(x, y, z,
                       cmap = 'hot',
                       edgecolor ='none')

fig.colorbar(surf, ax = ax,
             shrink = 0.5, aspect = 5)
plt.show()

Output:

the resulting 3d surface plot with gradient

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using axes.plot_surface.
  • Add colorbar to the figure using figure.colorbar (Refer this).

Example 6 – 3D surface plot having 2D contour projections

import numpy as np
import matplotlib.pyplot as plt

#defining the variables
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) )

#generating a figure and a 3D axes
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

#plotting the 3D surface plot
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')

plt.show()

Output:

the resulting 3d surface plot with a 2d contour project

The steps followed in the above example are:

  • Import required modules
  • Define the variables to plot
  • Generate the figure and a 3D axes
  • Plot the surface plot using axes.plot_surface.
  • Add contour projections using Axes.contourf method.

To understand more about Contour plots, refer this.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Chaitanya Betha

    I'm an undergrad student at IIT Madras interested in exploring new technologies. I have worked on various projects related to Data science, Machine learning & Neural Networks, including image classification using Convolutional Neural Networks, Stock prediction using Recurrent Neural Networks, and many more machine learning model training. I write blog articles in which I would try to provide a complete guide on a particular topic and try to cover as many different examples as possible with all the edge cases to understand the topic better and have a complete glance over the topic.

Scroll to Top