Open In App

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 creating an empty canvas at first. After that, we will be defining the axes of our 3D plot where we define that the projection of the plot will be in “3D” format. This helps us to create the 3D empty axes figure in the canvas. After this, if we show the plot using plt.show(), then it would look like the one shown in the output.



Example: Creating an empty 3D figure using Matplotlib




# importing numpy package from
# python library
import numpy as np
 
# importing matplotlib.pyplot package from
# python
import matplotlib.pyplot as plt
 
# Creating an empty figure
# or plot
fig = plt.figure()
 
# Defining the axes as a
# 3D axes so that we can plot 3D
# data into it.
ax = plt.axes(projection="3d")
 
# Showing the above plot
plt.show()

Output: 



Now, we have a basic idea about how to create a 3D plot on an empty canvas. Let us move to some 3D plotting examples. 

Examples of 3D plotting:

Example 1:

In the below example, we will be taking a simple curve in our 3D plot. Along with that, we will be plotting a range of points that have X-coordinate, Y-coordinate as well as Z-coordinate.  




# importing numpy package
import numpy as np
 
# importing matplotlib package
import matplotlib.pyplot as plt
 
# importing mplot3d from
# mpl_toolkits
from mpl_toolkits import mplot3d
 
# creating an empty canvas
fig = plt.figure()
 
# defining the axes with the projection
# as 3D so as to plot 3D graphs
ax = plt.axes(projection="3d")
 
# creating a wide range of points x,y,z
x=[0,1,2,3,4,5,6]
y=[0,1,4,9,16,25,36]
z=[0,1,4,9,16,25,36]
 
# plotting a 3D line graph with X-coordinate,
# Y-coordinate and Z-coordinate respectively
ax.plot3D(x, y, z, 'red')
 
# plotting a scatter plot with X-coordinate,
# Y-coordinate and Z-coordinate respectively
# and defining the points color as cividis
# and defining c as z which basically is a
# definition of 2D array in which rows are RGB
#or RGBA
ax.scatter3D(x, y, z, c=z, cmap='cividis');
 
# Showing the above plot
plt.show()

Output:

Explanation: 

Example 2:

In this example, we will be learning about how to do 3D plotting using figure.gca(). Here we will be creating a sine curve and a cosine curve with the values of x and y ranging from -5 to 5 with a gap of 1. Let us look at the code to understand the implementation. 




# importing matplotlib.pyplot from
# python
import matplotlib.pyplot as plt
 
# importing numpy package from
# python
import numpy as np
 
# creating a range of values for
# x,y,x1,y1  from -5 to 5 with
# a space of 1 between the elements
x = np.arange(-5,5,1)
y = np.arange(-5,5,1)
 
# creating a range of values for
# x,y,x1,y1  from -5 to 5 with
# a space of 0.6 between the elements
x1= np.arange(-5,5,0.6)
y1= np.arange(-5,5,0.6)
 
# Creating a mesh grid with x ,y and x1,
# y1 which creates an n-dimensional
# array
x, y = np.meshgrid(x, y)
x1,y1= np.meshgrid(x1,y1)
 
# Creating a sine function with the
# range of values from the meshgrid
z = np.sin(x * np.pi/2 )
 
# Creating a cosine function with the
# range of values from the meshgrid
z1= np.cos(x1* np.pi/2)
 
# Creating an empty figure for
# 3D plotting
fig = plt.figure()
 
# using fig.gca, we are creating a 3D
# projection plot in the empty figure
ax = fig.gca(projection="3d")
 
# Creating a wireframe plot with the x,y and
# z-coordinates respectively along with the
# color as red
surf = ax.plot_wireframe(x, y, z, color="red")
 
# Creating a wireframe plot with the points
# x1,y1,z1 along with the plot line as green
surf1 =ax.plot_wireframe(x1, y1, z1, color="green")
 
#showing the above plot
plt.show()

Output:

Explanation:

Example 3:

In the last and the final example, we will be creating two 3D graphs in a single figure/canvas, where we will be our 3D points. So let us move into our code implementation. 




#importing matplotlib.pyplot from
# python
import matplotlib.pyplot as plt
 
# importing numpy package from python
import numpy as np
 
# creating an empty figure for plotting
fig = plt.figure()
 
# defining a sub-plot with 1x2 axis and defining
# it as first plot with projection as 3D
ax = fig.add_subplot(1, 2, 1, projection='3d')
 
# creating a range of 12 elements in both
# X and Y
X = np.arange(12)
Y = np.linspace(12, 1)
 
# Creating a mesh grid of X and Y
X, Y = np.meshgrid(X, Y)
 
# Creating an expression X and Y and
# storing it in Z
Z = X*2+Y*3;
 
# Creating a wireframe plot with the 3 sets of
# values X,Y and Z
ax.plot_wireframe(X, Y, Z)
 
# Creating my second subplot with 1x2 axis and defining
# it as the second plot with projection as 3D
ax = fig.add_subplot(1, 2, 2, projection='3d')
 
# defining a set of points for X,Y and Z
X1 = [1,2,1,4,3,2,7,5,9]
Y1 = [8,2,7,4,3,6,1,8,9]
Z1 = [1,2,4,7,9,6,7,6,9]
 
# Plotting 3 points X1,Y1,Z1 with
# color as green
ax.plot(X1, Y1, Z1,color='green')
 
# Showing the above plot
plt.show()

Output:

Explanation: 

Key 3D Plots using Matplotlib:

 Surface Plot and Tri-surface plots

Here we will look at how to create a surface plot and a tri-surface plot. Here, we are integrating both the plots into a single figure so that we can understand the concept of subplots along with that of plots for a wide range of points to be plotted. So let us move to the implementation of the concept. Unlike wireframe plots, these plot’s surfaces will be filled with color.

Example: 




#importing matplotlib.pyplot from
# python
import matplotlib.pyplot as plt
 
# importing numpy package from python
import numpy as np
 
# creating an empty figure for plotting
fig = plt.figure()
 
# defining a sub-plot with 1x2 axis and defining
# it as first plot with projection as 3D
ax = fig.add_subplot(1, 2, 1, projection='3d')
 
# creating a range of values for
# x1,y1  from -1 to 1 with
# a space of 0.1 between the elements so that
# we can create a single curve in the plot
x1= np.arange(-1,1,0.1)
y1= np.arange(-1,1,0.1)
 
# Creating a mesh grid with x ,y and x1,
# y1 which creates an n-dimensional
# array
x1,y1= np.meshgrid(x1,y1)
 
# Creating a cosine function with the
# range of values from the meshgrid
z1= np.cos(x1* np.pi/2)
 
# Creating a wireframe plot with the points
# x1,y1,z1 along with the plot line as red
ax.plot_surface(x1, y1, z1, color="red")
 
# Creating my second subplot with 1x2 axis and defining
# it as the second plot with projection as 3D
ax = fig.add_subplot(1, 2, 2, projection='3d')
 
# defining a set of points for X1,Y1 and Z1
X1 = [1,2,1,4,3,2,7,5,9]
Y1 = [8,2,7,4,3,6,1,8,9]
Z1 = [1,2,4,7,9,6,7,6,9]
 
# Plotting 3 points X1,Y1,Z1 with
# color as purple
ax.plot_trisurf(X1, Y1, Z1,color='purple')
 
# Showing the above plot
plt.show()

Output: 

Explanation:

Contour plots and Filled Contour plots

Here, we will be looking at contour and filled contour plots. Since both the plots are similar type, we are using a subplot again for plotting the points. Contour plot is a way of showing a 3D graph by plotting constant z-slices. Filled contour fills the areas that were shown by the line in contour plots. 




# importing axes3d from mpl_toolkits.mplot
# module in python
from mpl_toolkits.mplot3d import axes3d
 
# importing matplotlib package from python
import matplotlib.pyplot as plt
 
#importing numpy package from
# python library
import numpy as np
 
# Creating an empty figure
fig = plt.figure()
 
# Creating a subplot where we are
# defining the projection as 3D projection
ax = fig.add_subplot(1,2,1, projection='3d')
 
# Creating a set of testing data using
# get_test_data from axes3d module in
# python. It creates a set of nD arrays
# for each of the variables X,Y,Z
X, Y, Z = axes3d.get_test_data(0.07)
#Plotting the contour plot with the
# following range of nD arrays
plot = ax.contour(X, Y, Z)
 
# Adding a second subplot in our figure with
# the projection as a 3D projection
ax=fig.add_subplot(1,2,2,projection='3d')
 
# Adding a range of values to the variables X1,Y1
X1=[1,2,3,4,5,6,7]
Y1=[1,2,3,4,5,6,7]
 
# Creating a meshgrid of X1 and Y1
X1, Y1 = np.meshgrid(X1,Y1)
# Creating an expression for Z1 with the
# help of X1 and Y1
Z1=(X1+4)*5+(Y1-5)/2
 
# Creating a contour plot
plot2 = ax.contourf(X1, Y1, Z1)
 
# Showing the above plot
plt.show()

Output:

Explanation:

Polygon plots

Here, we will be exploring a polygon plot. This plot is different from the ones that were plotted in the earlier examples. In this plot, we will be plotting a continuous set of points at different axes points of z. Let’s move to the implementation.

Example:




# import Axes3D from mpl_toolkits.mplot3d
# from python
from mpl_toolkits.mplot3d import Axes3D
 
# importing PolyCollection from
# matplotlib.collections module
from matplotlib.collections import PolyCollection
 
#importing matplotlib.pyplot from
# python
import matplotlib.pyplot as plt
 
# importing numpy package from
# python
import numpy as np
 
# Creating an empty figure
fig = plt.figure()
 
# Creating a 3D projection using
# fig.gca
ax = fig.gca(projection='3d')
 
# Creating a wide range of elements
# using numpy package from python
xs = np.arange(0, 1, 0.1)
# Creating an empty list
verts = []
# Creating a range of values on
# Z-Axis
zs = [0.0, 0.2, 0.4, 0.6,0.8]
# Looping through all the values in zs
# and creating random values in ys using
# np.random.rand() which creates a range of
# elements in ys and we are appending each of them
# inside verts[]
for z in zs:
    ys = np.random.rand(len(xs))
    verts.append(list(zip(xs, ys)))
# using polycollection, we are providing a
# series of vertices to poly so as to
# plot our required plot
poly = PolyCollection(verts)
# Using add_collection3d, we are plotting
# you are required polygon plot where we define
# zs with the range of values we defined in our
# list zs and also the zdir as Y-Axis
ax.add_collection3d(poly,zs=zs,zdir='y')
# Showing the required plot
plt.show()

Output: 

Explanation: 

Quiver plots

Here, we will be learning about the quiver plot in matplotlib. A quiver plot helps us to plot a 3d field of arrows in order to define the specified points. We can customize the arrows in various ways. Let us look into the code implementation.

Example: 




# import axes3d from mpl_toolkits.mplot3d
from mpl_toolkits.mplot3d import axes3d
 
# import matplotlib.pyplot from python
import matplotlib.pyplot as plt
 
# import numpy from python
import numpy as np
 
# Creating an empty figure
# to plot a 3D graph
fig = plt.figure()
 
# Creating a 3Dprojection for
# our 3D plots using fig.gca
ax = fig.gca(projection='3d')
 
# Creating a meshgrid for the range
# of values in X,Y,Z
x, y, z = np.meshgrid([1,2,5,2,4,8,3,3,1],[6,4,3,1,6,2,7,8,2],[1,2,5,2,4,8,3,3,1])
 
# Creating expressions for u,v,w
# with the help of x,y and z
# which will form the direction vectors
u = x*2+y*3+z*3
v = (x+3)*(y+5)*(z+7)
w = x+y+z
 
# Creating a quiver plot with length of the direction
# vector length as 0.2 ad normalise as true
ax.quiver(x, y, z, u, v, w, length=0.2, normalize=True)
 
#showing the above plot
plt.show()

Output: 

Explanation:

 2D data to be plotted in 3D plots

Here, we will be taking a set of 2D points to be plotted in a specific axis in our 3D plot because we cannot plot a 2D point in a 3D plane with all the coordinates. So a specific axis needs to be defined for plotting the 2D points. So let’s see the code of the plot. 




# importing numpy package
import numpy as np
# importing matplotlib package
import matplotlib.pyplot as plt
 
# Creating an empty canvas(figure)
fig = plt.figure()
 
# Using the gca function, we are defining
# the current axes as a 3D projection
ax = fig.gca(projection='3d')
 
# Labelling X-Axis
ax.set_xlabel('X-Axis')
 
# Labelling Y-Axis
ax.set_ylabel('Y-Axis')
 
# Labelling Z-Axis
ax.set_zlabel('Z-Axis')
 
# Creating 10 values for X
x = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8]
 
# Creating 10 values for Y
y = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8]
 
# Creating 10 random values for Y
z=[1,2,4,5,6,7,8,9,10,11]
 
# zdir='z' fixes all the points to zs=0 and
# (x,y) points are plotted in the x-y axis
# of the graph
ax.plot(x, y, zs=0, zdir='z')
 
# zdir='y' fixes all the points to zs=0 and
# (x,y) points are plotted in the x-z axis of the
# graph
ax.plot(x, y, zs=0, zdir='y')
 
# Showing the above plot
plt.show()

Output: 

Explanation:

 


Article Tags :