Comprehensive Implementation of 3D Geometric Objects Plotting with Matplotlib: Cube, Sphere, and Vector

Dec 04, 2025 · Programming · 13 views · 7.8

Keywords: Matplotlib | 3D Visualization | Geometric Object Plotting | Python Programming | Scientific Computing

Abstract: This article provides a detailed guide on plotting basic geometric objects in 3D space using Matplotlib, including a wireframe cube centered at the origin with side length 2, a wireframe sphere with radius 1, a point at the origin, and a vector from the origin to (1,1,1). Through in-depth analysis of core code implementation, the paper explores key techniques such as 3D coordinate generation, wireframe plotting, and custom arrow class design, offering complete Python code examples and optimization suggestions to help readers master advanced 3D visualization techniques with Matplotlib.

Fundamental Principles of 3D Geometric Object Plotting

In the fields of scientific computing and data visualization, Matplotlib, as one of the most popular plotting libraries in Python, provides powerful 3D visualization capabilities. Through the mpl_toolkits.mplot3d module, users can create complex 3D graphics. This article will use the plotting of a cube, sphere, point, and vector as examples to deeply explore the core implementation methods of 3D object rendering.

Environment Configuration and Basic Setup

First, necessary libraries must be imported and 3D axes created:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

The key here is the projection='3d' parameter, which converts 2D axes into a 3D coordinate system. set_aspect("equal") ensures consistent scaling across all three axes, preventing geometric distortion.

Implementation of Wireframe Cube Plotting

Plotting a cube with side length 2 centered at the origin requires generating all vertices and connecting adjacent edges:

r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

The core logic of this code is:

  1. Using product(r, r, r) to generate the 8 vertex coordinates of the cube (all combinations from -1,-1,-1 to 1,1,1)
  2. Obtaining all vertex pairs through combinations(..., 2)
  3. Filtering adjacent vertices (Manhattan distance of 2) with the condition np.sum(np.abs(s-e)) == r[1]-r[0]
  4. Drawing connecting lines using ax.plot3D

This method avoids drawing duplicate edges and automatically handles all 12 edges.

Parametric Plotting of Wireframe Sphere

The sphere is plotted using parametric equations:

u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

Spherical coordinate parametric equations are employed here:

The plot_wireframe method converts the parametric surface into wireframe display, with red lines clearly showing the sphere structure.

Special Handling of Point and Vector

Plotting a point at the origin is relatively straightforward:

ax.scatter([0], [0], [0], color="g", s=100)

The s parameter of the scatter method controls point size, with green color making it stand out in the figure.

Vector plotting requires a custom arrow class, as Matplotlib doesn't directly support 3D arrows:

from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs
    
    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)

Key aspects of the custom Arrow3D class:

  1. Inherits from FancyArrowPatch to obtain 2D arrow functionality
  2. Stores 3D coordinates in __init__
  3. Uses proj3d.proj_transform in the draw method to project 3D coordinates to the 2D display plane
  4. mutation_scale controls arrow size, arrowstyle="-|>" defines arrow style

Complete Code Integration and Display

After combining all components, the final figure is displayed:

plt.show()

The generated figure simultaneously displays a blue cube, red sphere, green origin point, and black vector, all centered at the origin, forming a clear spatial relationship presentation.

Technical Summary and Extensions

This implementation demonstrates several key techniques in Matplotlib 3D plotting:

  1. Coordinate Generation Techniques: Efficient generation of geometric vertices using product and combinations
  2. Parametric Surfaces: Generating smooth spherical surfaces through spherical coordinate equations
  3. Custom Visualization Elements: Extending 3D functionality by inheriting existing classes
  4. Projection Transformation: Understanding the mechanism of 3D to 2D projection

For more complex applications, consider:

By mastering these techniques, users can create various complex 3D scientific visualizations to meet research and engineering application requirements.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.