The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/three-dimensional-plotting-in-python-using-matplotlib/
Open In App

Three-dimensional Plotting in Python using Matplotlib

Last Updated : 22 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

python-matplotlib-3d-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 Graph Using 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:
 

download-_3_

3D line plot graph using the matplotlib library

3-Dimensional Scattered Graph Using 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:
 

python-matplotib-3d-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:

python-matplotlib-3d-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:
 

python-matplotlib-3d-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:

download

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:

download-_1_

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:

download-_2_

Mobius strip plot using matplotlib library 



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 Surface plotting in Python using Matplotlib
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
4 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 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
Plotting Various Sounds on Graphs using Python and Matplotlib
In this article, we will explore the way of visualizing sounds waves using Python and Matplotlib. Modules Needed 1. Matplotlib: Install Matplotlib using the below command: pip install matplotlib 2. Numpy: Numpy gets installed automatically installed with Matplotlib. Although, if you face any import error, use the below command to install Numpy pip
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
3 min read
Different plotting using pandas and matplotlib
We have different types of plots in matplotlib library which can help us to make a suitable graph as you needed. As per the given data, we can make a lot of graph and with the help of pandas, we can create a dataframe before doing plotting of data. Let's discuss the different types of plot in matplotlib by using Pandas. Use these commands to instal
4 min read
Plotting A Square Wave Using Matplotlib, Numpy And Scipy
Prerequisites: linspace, Mathplotlib, Scipy A square wave is a non-sinusoidal periodic waveform in which the amplitude alternates at a steady frequency between the fixed minimum and maximum values, with the same duration at minimum and maximum. Graphical representations are always easy to understand and are adopted and preferable before any written
2 min read
Plotting a Sawtooth Wave using Matplotlib
Prerequisites: MatplotlibScipy A sawtooth waveform is a non-sinusoidal waveform because its teeth look like a saw. In an inverse (or reverse) sawtooth waveform the wave suddenly ramps downwards and then rises sharply. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we plot sawtooth
1 min read
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand
2 min read
Plotting random points under sine curve in Python Matplotlib
While conducting numerous scientific studies, plotting random points may be quite helpful. We frequently need to plot random points with a certain nature of graphs and charts when running test cases. This article shows you how to use Python to plot random points on a sine curve. To get started, we will need the following Python Modules: NumPy - Thi
2 min read
Plotting back-to-back bar charts Matplotlib
In this article, we will learn how to plot back-to-back bar charts in matplotlib in python. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It w
2 min read
Introduction to 3D Plotting with Matplotlib
In this article, we will be learning about 3D plotting with Matplotlib. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, Matplotlib.pyplot.gca(), etc. Creating an Empty 3D Plot: In the below code, we will be creati
15+ min read
Plotting In A Non-Blocking Way With Matplotlib
When we plot a graph with Matplotlib, by default the execution of the code is stopped/blocked when it is viewed/drawn until the view window is closed. However, in certain cases, one may want to remove this blocking behavior and see the graph as soon as it is plotted or updated without blocking the program execution. This article addresses this issu
5 min read
Plotting Only the Upper/Lower Triangle of a Heatmap in Matplotlib
Heatmaps are a powerful visualization tool used to represent data in a matrix format, where individual values are represented by colors. They are particularly useful for visualizing correlation matrices, where the symmetric nature of the matrix makes it redundant to display both the upper and lower triangles. This article will guide you through the
4 min read
Plotting Bar Graph in Matplotlib from a Pandas Series
Bar graphs are one of the most common types of data visualizations used to represent categorical data with rectangular bars. Each bar's height or length corresponds to the value it represents. In Python, the combination of Pandas and Matplotlib libraries provides a powerful toolset for creating bar graphs. This article will guide you through the pr
3 min read
Python | Geographical plotting using plotly
Geographical plotting is used for world map as well as states under a country. Mainly used by data analysts to check the agriculture exports or to visualize such data. plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many
2 min read
Plotting graphs using Python's plotly and cufflinks module
plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. cufflink connects plotly with pandas to create g
2 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Python | Plotting bar charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points
6 min read
Python | Plotting Radar charts in excel sheet using XlsxWriter module
Prerequisite:Create and Write on excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Radar charts using realtime data. Charts are composed of at least one series of one or more data points.
6 min read
Python | Plotting scatter charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data p
10 min read
Article Tags :
Practice Tags :