Plotting points on the surface of a sphere in Python's Matplotlib

To plot points on the surface of a sphere in Python, we can use Matplotlib's plot_surface() method with 3D projection. This creates a visual representation of a sphere using spherical coordinates converted to Cartesian coordinates.

Steps to Create a Sphere

  • Create a new figure using figure() method

  • Add a 3D subplot using add_subplot() with 3D projection

  • Generate spherical coordinates using numpy.mgrid

  • Convert spherical coordinates (u, v) to Cartesian coordinates (x, y, z)

  • Plot the surface using plot_surface() method

  • Display the figure using show() method

Basic Sphere Example

Here's how to create a basic sphere surface ?

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

# Create spherical coordinates
u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:20j]

# Convert to Cartesian coordinates
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)

# Plot the sphere surface
ax.plot_surface(x, y, z, cmap=plt.cm.YlGnBu_r)
plt.show()

Understanding the Mathematics

The sphere is created using spherical coordinate conversion ?

  • u: Azimuthal angle (0 to 2?) - rotation around z-axis

  • v: Polar angle (0 to ?) - angle from positive z-axis

  • x = cos(u) × sin(v): X-coordinate

  • y = sin(u) × sin(v): Y-coordinate

  • z = cos(v): Z-coordinate

Customizing the Sphere

You can modify the sphere's appearance and resolution ?

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(projection='3d')

# Higher resolution sphere
u, v = np.mgrid[0:2 * np.pi:50j, 0:np.pi:25j]

# Sphere with radius 2
radius = 2
x = radius * np.cos(u) * np.sin(v)
y = radius * np.sin(u) * np.sin(v)
z = radius * np.cos(v)

# Custom colormap and transparency
ax.plot_surface(x, y, z, cmap='viridis', alpha=0.8)

# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Customized Sphere Surface')

plt.show()

Key Parameters

Parameter Purpose Example Values
mgrid resolution Controls sphere smoothness 30j, 50j (higher = smoother)
cmap Color scheme 'viridis', 'plasma', 'YlGnBu_r'
alpha Transparency 0.0 to 1.0

Conclusion

Creating sphere surfaces in Matplotlib involves converting spherical coordinates to Cartesian coordinates and using plot_surface(). Adjust the mgrid resolution for smoother spheres and experiment with different colormaps for visual appeal.

Updated on: 2026-03-25T20:02:00+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements