Matplotlib - 3D Volumes



A 3D volume represents the space occupied by an object in three-dimensions. When we talk about 3D, we are considering objects that have depth, not just length and width. The 3D volume of an object is the product of length, width, and height which are represented by the X, Y, and Z coordinates.

Imagine you have a regular book. You can see its width and height when looking at it from the front cover, and its length when you look at it from the side. Now, if you imagine that book as a cube, you will see that it has not just length and width, but also depth or height. That's what makes it three-dimensional −

3D Volumes

3D Volumes in Matplotlib

In Matplotlib, 3D volumes refer to the visual representation of a shape that occupies space across three dimensions. Various functions are available for generating 3D volumes of different shapes within Matplotlib.

One commonly used function for this purpose is the plot_surface() function found in the "mpl_toolkits.mplot3d" module. This function accepts arrays containing the X, Y, and Z coordinates and creates a 3D volume plot by connecting these coordinates to form a solid shape.

Lets start by drawing a basic 3D volume plot.

Basic 3D Volume Plot

In Matplotlib, creating a basic 3D volume plot is like generating a three-dimensional model of a shape. Imagine you are building a sculpture with clay, but in this case, you are using numbers to define where each point of the shape should be in space.

With Matplotlib, you can easily visualize these shapes by providing the X, Y, and Z coordinates, and the library will display them into a three-dimensional plot, allowing you to see the shape from different angles.

Example

In the following example, we are creating a basic 3D volume plot in Matplotlib. We use two Numpy arrays: the first array defines the "vertices", while the second array defines the "faces" of the cube −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

# Defining cube vertices using NumPy array
vertices = np.array([
    [1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1],
    [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]
])

# Defining cube faces using NumPy array reshaping
faces = np.array([
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [0, 1, 5, 4],
    [2, 3, 7, 6],
    [1, 2, 6, 5],
    [0, 3, 7, 4]
])

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D cube
ax.add_collection3d(Poly3DCollection([vertices[face] for face in faces], facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

# Customizing the plot
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Cube')

# Displaying the plot
plt.show()

Output

Following is the output of the above code −

Basic 3D Volume Plot

3D Cone Volume

A 3D cone volume in Matplotlib is a visual representation of a three-dimensional triangle. The data points define a shape with a circular base that narrows as it extends upwards, creating a pointed tip. We can imagine it as a triangle stacked on a circle.

Example

In here, we are creating a 3D cone volume by parametrizing the X, Y, and Z coordinates with parameter (u) and height (v) of the cone. The resultant plots create a conical shape like an ice-cream cone −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating a cone
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, 1, 100)
u, v = np.meshgrid(u, v)
r = 1
h = 2
x = r * (1 - v) * np.cos(u)
y = r * (1 - v) * np.sin(u)
z = h * v

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D cone
ax.plot_surface(x, y, z, color='green', alpha=0.6)

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Cone')

# Displaying the plot
plt.show()

Output

Output of the above code is as follows −

3D Cone Volume

3D Sphere Volume

In Matplotlib, a 3D sphere volume is a visual representation of a round object with no edges or corners. We can imagine it as multiple circles stacked side by side, giving it depth to create a 3 dimension shape.

Example

The following example creates a 3D sphere sphere by parametrizing the X, Y, and Z coordinates using the angles (u and v) and the radius (r) of the sphere −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating sphere
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
u, v = np.meshgrid(u, v)
r = 1
x = r * np.sin(v) * np.cos(u)
y = r * np.sin(v) * np.sin(u)
z = r * np.cos(v)

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D sphere
ax.plot_surface(x, y, z, color='orange', alpha=0.6)

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Sphere')

# Displaying the plot
plt.show()

Output

After executing the above code, we get the following output −

3D Sphere

3D Parallelepiped Volume

A 3D parallelepiped volume in Matplotlib is a representation of a three-dimensional figure with six parallelogram faces. We can think of it as a shape with six faces, where all the opposite faces are parallel to each other.

Example

Now, we are using two Numpy arrays to create a 3D parallelepiped. The first array creates the eight vertices, while the second array creates the six parallel faces of the parallelepiped −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

# Defining parallelogram vertices using NumPy array
vertices = np.array([
    [0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
    [0.5, 0.5, 1], [1.5, 0.5, 1], [1.5, 1.5, 1], [0.5, 1.5, 1]
])

# Defining parallelogram faces using NumPy array reshaping
faces = np.array([
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [0, 1, 5, 4],
    [2, 3, 7, 6],
    [1, 2, 6, 5],
    [0, 3, 7, 4]
])

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D parallelogram
ax.add_collection3d(Poly3DCollection([vertices[face] for face in faces], facecolors='yellow', linewidths=1, edgecolors='black', alpha=.25))

# Customizing the plot
ax.set_xlim([0, 2])
ax.set_ylim([0, 2])
ax.set_zlim([0, 2])
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Parallelepiped')

# Displaying the plot
plt.show()

Output

The output obtained is as shown below −

3D Parallelepiped
Advertisements