⬡ Hub
Skip to content

Matplotlib: 3D Plotting

Matplotlib can also be used for creating 3D plots, providing a way to visualize data with three spatial dimensions. The mplot3d toolkit, which comes with Matplotlib, provides the necessary functionality.

To use 3D plotting, you need to import Axes3D from mpl_toolkits.mplot3d. Once imported, you can create 3D axes by passing projection='3d' to add_subplot().

1. Basic 3D Scatter Plot

A 3D scatter plot is used to display the relationship between three numerical variables.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D # Required for 3D projections

# Generate some random data
np.random.seed(42)
num_points = 100
x = np.random.rand(num_points) * 10
y = np.random.rand(num_points) * 10
z = np.random.rand(num_points) * 10

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d') # Create a 3D subplot

# Plot the scatter points
ax.scatter(x, y, z, c='skyblue', marker='o', s=50, alpha=0.8)

# Set labels
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('Basic 3D Scatter Plot')
plt.show()

2. Basic 3D Line Plot

Similar to 2D line plots, 3D line plots connect a series of points in 3D space.

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

# Generate data for a 3D helix
t = np.linspace(-2 * np.pi, 2 * np.pi, 500)
x = np.sin(t)
y = np.cos(t)
z = t

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

# Plot the 3D line
ax.plot(x, y, z, color='purple', linewidth=2)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('3D Helix Line Plot')
plt.show()

3. 3D Surface Plots

Surface plots are used to visualize functions of two variables, showing a 3D surface. They require a meshgrid for x and y coordinates.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # Colormap for surfaces

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

# Create the meshgrid for x and y values
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)

# Define a function to plot (e.g., a 2D sinc function)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R) / R # Z as a function of X and Y

# Plot the surface
ax.plot_surface(X, Y, Z, cmap=cm.viridis, linewidth=0, antialiased=False)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('3D Surface Plot of Sinc Function')
plt.show()

4. 3D Wireframe Plots

Wireframe plots are similar to surface plots but only show the lines connecting the data points, creating a grid-like appearance.

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

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

# Create the meshgrid for x and y values
X = np.arange(-5, 5, 0.5)
Y = np.arange(-5, 5, 0.5)
X, Y = np.meshgrid(X, Y)

# Define a function to plot
Z = np.sin(np.sqrt(X**2 + Y**2))

# Plot the wireframe
ax.plot_wireframe(X, Y, Z, color='blue', rstride=1, cstride=1)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('3D Wireframe Plot')
plt.show()

5. Customizing 3D Plots

You can customize views, add titles, labels, and more.

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

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

x = np.random.rand(100) * 10
y = np.random.rand(100) * 10
z = np.sin(x) + np.cos(y) # Z is a function of x and y

ax.scatter(x, y, z, c=z, cmap='plasma', s=80, alpha=0.7)

ax.set_xlabel('Feature X', fontsize=12, color='red')
ax.set_ylabel('Feature Y', fontsize=12, color='green')
ax.set_zlabel('Feature Z', fontsize=12, color='blue')

ax.set_title('Customized 3D Scatter Plot', fontsize=16)

# Customize view angle (elevation and azimuth)
ax.view_init(elev=20, azim=-120) # elev: elevation angle, azim: azimuthal angle

# Add a color bar
m = plt.cm.ScalarMappable(cmap='plasma')
m.set_array(z)
fig.colorbar(m, ax=ax, shrink=0.5, aspect=5, label='Value of Z')

plt.tight_layout()
plt.show()

Further Topics:

  • 3D bar plots
  • 3D contour plots
  • Quiver plots
  • Polygons and patches in 3D
  • Interactive 3D plots (e.g., using mpl_toolkits.mplot3d.art3d)

3D plotting adds another dimension to your data visualization capabilities, allowing you to represent complex relationships and structures effectively.