Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (2025)

Last Updated : 22 Dec, 2023

Improve

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 using Matplotlib

We will first start with plotting the 3D axis using the Matplotlib library.For plotting the 3D axis we just have to change the projection parameter of plt.axes() from None to 3D.

Python3

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

ax = plt.axes(projection='3d')

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (1)

Plotting 3D axes using matplotlib

With the above syntax three -dimensional axes are enabled and data can be plotted in 3 dimensions. 3 dimension graph gives a dynamic approach and makes data more interactive. Like 2-D graphs, we can use different ways to represent to plot 3-D graphs. We can make a scatter plot, contour plot, surface plot, etc. Let’s have a look at different 3-D plots.
Graphs with lines and points are the simplest 3-dimensional graph. We will use ax.plot3d and ax.scatter functions to plot line and point graph respectively.

3-Dimensional Line GraphUsing Matplotlib

For plotting the 3-Dimensional line graph we will use the mplot3d function from the mpl_toolkits library. For plotting lines in 3D we will have to initialize three variable points for the line equation. In our case, we will define three variables as x, y, and z.

Python3

# importing mplot3d toolkits, numpy and matplotlib

from mpl_toolkits import mplot3d

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

# syntax for 3-D projection

ax = plt.axes(projection ='3d')

# defining all 3 axis

z = np.linspace(0, 1, 100)

x = z * np.sin(25 * z)

y = z * np.cos(25 * z)

# plotting

ax.plot3D(x, y, z, 'green')

ax.set_title('3D line plot geeks for geeks')

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (2)

3D line plot graph using the matplotlib library

3-Dimensional Scattered GraphUsing Matplotlib

To plot the same graph using scatter points we will use the scatter() function from matplotlib. It will plot the same line equation using distinct points.

Python3

# importing mplot3d toolkits

from mpl_toolkits import mplot3d

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

# syntax for 3-D projection

ax = plt.axes(projection ='3d')

# defining axes

z = np.linspace(0, 1, 100)

x = z * np.sin(25 * z)

y = z * np.cos(25 * z)

c = x + y

ax.scatter(x, y, z, c = c)

# syntax for plotting

ax.set_title('3d Scatter plot geeks for geeks')

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (3)

3D point plot using Matplotlib library

Surface Graphs using Matplotlib library

Surface graphs and Wireframes graph work on gridded data. They take the grid value and plot it on a three-dimensional surface. We will use the plot_surface() function to plot the surface plot.

Python3

# importing libraries

from mpl_toolkits import mplot3d

import numpy as np

import matplotlib.pyplot as plt

# defining surface and axes

x = np.outer(np.linspace(-2, 2, 10), np.ones(10))

y = x.copy().T

z = np.cos(x ** 2 + y ** 3)

fig = plt.figure()

# syntax for 3-D plotting

ax = plt.axes(projection='3d')

# syntax for plotting

ax.plot_surface(x, y, z, cmap='viridis',\

edgecolor='green')

ax.set_title('Surface plot geeks for geeks')

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (4)

Surface plot using matplotlib library

Wireframes graph using Matplotlib library

For plotting the wireframes graph we will use the plot_wireframe() function from the matplotlib library.

Python3

from mpl_toolkits import mplot3d

import numpy as np

import matplotlib.pyplot as plt

# function for z axis

def f(x, y):

return np.sin(np.sqrt(x ** 2 + y ** 2))

# x and y axis

x = np.linspace(-1, 5, 10)

y = np.linspace(-1, 5, 10)

X, Y = np.meshgrid(x, y)

Z = f(X, Y)

fig = plt.figure()

ax = plt.axes(projection ='3d')

ax.plot_wireframe(X, Y, Z, color ='green')

ax.set_title('wireframe geeks for geeks');

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (5)

3D wireframe graph using the matplotlib library

Contour Graphs using Matplotlib library

The contour graph takes all the input data in two-dimensional regular grids, and the Z data is evaluated at every point. We use the ax.contour3D function to plot a contour graph. Contour plots are an excellent way to visualize optimization plots.

Python3

def function(x, y):

return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-10, 10, 40)

y = np.linspace(-10, 10, 40)

X, Y = np.meshgrid(x, y)

Z = function(X, Y)

fig = plt.figure(figsize=(10, 8))

ax = plt.axes(projection='3d')

ax.plot_surface(X, Y, Z, cmap='cool', alpha=0.8)

ax.set_title('3D Contour Plot of function(x, y) =\

sin(sqrt(x^2 + y^2))', fontsize=14)

ax.set_xlabel('x', fontsize=12)

ax.set_ylabel('y', fontsize=12)

ax.set_zlabel('z', fontsize=12)

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (6)

3D contour plot of a function using matplotlib

Plotting Surface Triangulations In Python

The above graph is sometimes overly restricted and inconvenient. So by this method, we use a set of random draws. The function ax.plot_trisurf is used to draw this graph. It is not that clear but more flexible.

Python3

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

from matplotlib.tri import Triangulation

def f(x, y):

return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)

y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)

Z = f(X, Y)

tri = Triangulation(X.ravel(), Y.ravel())

fig = plt.figure(figsize=(10, 8))

ax = fig.add_subplot(111, projection='3d')

ax.plot_trisurf(tri, Z.ravel(), cmap='cool', edgecolor='none', alpha=0.8)

ax.set_title('Surface Triangulation Plot of f(x, y) =\

sin(sqrt(x^2 + y^2))', fontsize=14)

ax.set_xlabel('x', fontsize=12)

ax.set_ylabel('y', fontsize=12)

ax.set_zlabel('z', fontsize=12)

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (7)

Surface triangulation graph of a contour plot using matplotlib

Plotting Möbius strip In Python

Möbius strip also called the twisted cylinder, is a one-sided surface without boundaries. To create the Möbius strip think about its parameterization, it’s a two-dimensional strip, and we need two intrinsic dimensions. Its angle range from 0 to 2 pie around the loop and its width ranges from -1 to 1.

Python3

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

# Define the parameters of the Möbius strip

R = 2

# Define the Möbius strip surface

u = np.linspace(0, 2*np.pi, 100)

v = np.linspace(-1, 1, 100)

u, v = np.meshgrid(u, v)

x = (R + v*np.cos(u/2)) * np.cos(u)

y = (R + v*np.cos(u/2)) * np.sin(u)

z = v * np.sin(u/2)

# Create the plot

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

# Plot the Möbius strip surface

ax.plot_surface(x, y, z, alpha=0.5)

# Set plot properties

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

ax.set_title('Möbius Strip')

# Set the limits of the plot

ax.set_xlim([-3, 3])

ax.set_ylim([-3, 3])

ax.set_zlim([-3, 3])

# Show the plot

plt.show()

Output:

Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (8)

Mobius strip plot using matplotlib library



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
Three-dimensional Plotting in Python using Matplotlib - GeeksforGeeks (2025)

FAQs

What is three-dimensional plotting in Matplotlib? ›

The most basic three-dimensional plot is a line or collection of scatter plot created from sets of (x, y, z) triples. In analogy with the more common two-dimensional plots discussed earlier, these can be created using the ax. plot3D and ax. scatter3D functions.

How do I plot a 3D line in Matplotlib? ›

How to plot a 3D continuous line in Matplotlib?
  1. Set the figure size and adjust the padding between and around the subplots.
  2. Create x and y data points using numpy.
  3. Create z data points using x and y data points.
  4. Create a new figure or activate an existing figure using figure() method.
Jun 3, 2021

How do I plot a 3D box in Matplotlib? ›

The 3d plot is enabled by importing the mplot3d toolkit., which comes with your standard Matplotlib. After importing, 3D plots can be created by passing the keyword projection=”3d” to any of the regular axes creation functions in Matplotlib.

How to plot 3 variables in Matplotlib? ›

How to plot 3 variables in Matplotlib? You can plot three variables by considering one as time or x-axis, and the other two as y-values, or by using a 3D plot.

How to plot a 3D matrix in Matplotlib? ›

Creating a 3D plot in Matplotlib from a 3D numpy array
  1. Create a new figure or activate an existing figure using figure() method.
  2. Add an '~. axes. ...
  3. Create a random data of size=(3, 3, 3).
  4. Extract x, y, and z data from the 3D array.
  5. Plot 3D scattered points on the created axis.
  6. To display the figure, use show() method.
May 15, 2021

How do I make a 3D plot in Matplotlib interactive? ›

To generate an interactive 3D plot first import the necessary packages and create a random dataset. Now using Axes3D(figure) function from the mplot3d library we can generate a required plot directly. Pass the data to the 3D plot and configure the title and labels.

How do you title a 3D plot in Matplotlib? ›

To add a title, we simply use the set_title() function in Matplotlib. To set axis labels, we will use the set_xlabel(), set_ylabel() and set_zlabel() functions in Matplotlib. We can change the type of markers in our 3D plots by changing the markers parameter in scatter() method.

Is Matplotlib a 2D or 3D plotting library? ›

Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures.

How to plot 3D surface matplotlib? ›

We can create a 3d surface plot in Matplotlib using the plot_surface() function in "mpl_toolkits. mplot3d" module. It takes the X, Y, and Z coordinates as arrays and creates a continuous graph by joining the three coordinates.

How do I plot points in Matplotlib 3D? ›

Generally 3D scatter plot is created by using ax. scatter3D() the function of the matplotlib library which accepts a data sets of X, Y and Z to create the plot while the rest of the attributes of the function are the same as that of two dimensional scatter plot.

Which is a special kind of plot in 3D graphs of matplotlib? ›

Answer: The different types of 3D plots available in Matplotlib include: 3D scatter plots (scatter) 3D line plots (plot) 3D surface plots (plot_surface)

How do you plot a 3D bar plot in Python? ›

Process
  1. Import necessary libraries.
  2. Import styles library.
  3. Load the data sample.
  4. Use bar3D() to plot 3D bar chart.

How do I make a 3D histogram in matplotlib? ›

Create the Histogram

Now that we have our data, we can create the 3D histogram. We will use NumPy's histogram2d() function to create a 2D histogram of our data, and then use Matplotlib's bar3d() function to create a 3D bar graph of the histogram.

How do you create a 3 dimensional list in Python? ›

Using nested for loops:

Create an empty list lst to hold the 3D list. Loop through the range x to create the first dimension of the 3D list. Within the x loop, create an empty list lst_2d to hold the 2D list for each x element. Loop through the range y to create the second dimension of the 3D list.

How do you plot a 3D interactive plot in Python? ›

To generate an interactive 3D plot first import the necessary packages and create a random dataset. Now using Axes3D(figure) function from the mplot3d library we can generate a required plot directly. Pass the data to the 3D plot and configure the title and labels.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Jamar Nader

Last Updated:

Views: 6455

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.