Creating a 3D plot in Matplotlib from a 3D numpy array

To create a 3D plot from a 3D numpy array, we need to extract the x, y, and z coordinates from the array and use Matplotlib's 3D plotting capabilities. This is commonly used for visualizing 3D data points or spatial distributions.

Steps to Create a 3D Plot

  • Create a new figure using figure() method
  • Add a 3D subplot using add_subplot() with projection='3d'
  • Create or prepare your 3D numpy array data
  • Extract x, y, and z coordinates from the 3D array
  • Plot the points using scatter() method
  • Display the figure using show() method

Example

Here's how to create a 3D scatter plot from a random 3D numpy array ?

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

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

# Create figure and 3D axis
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create random 3D data
data = np.random.random(size=(3, 3, 3))

# Extract coordinates where data is non-zero
z, x, y = data.nonzero()

# Create 3D scatter plot
ax.scatter(x, y, z, c=z, alpha=1)

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

plt.show()

Working with Actual 3D Data

You can also plot actual data values from your 3D array instead of just indices ?

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

# Create 3D data with actual values
x = np.linspace(0, 4, 10)
y = np.linspace(0, 4, 10)
z = np.linspace(0, 4, 10)

# Create meshgrid for 3D coordinates
X, Y, Z = np.meshgrid(x, y, z)

# Create some 3D function values
values = np.sin(X) * np.cos(Y) * np.sin(Z)

# Find points where values are above a threshold
threshold = 0.5
mask = values > threshold

# Extract coordinates where condition is met
x_points = X[mask]
y_points = Y[mask]
z_points = Z[mask]
color_values = values[mask]

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

scatter = ax.scatter(x_points, y_points, z_points, 
                    c=color_values, cmap='viridis', alpha=0.7)

# Add colorbar and labels
plt.colorbar(scatter)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Plot from 3D Array')

plt.show()

Key Points

  • nonzero() method returns indices where array elements are non-zero
  • The projection='3d' parameter is essential for 3D plotting
  • Color mapping with c parameter adds visual depth to the plot
  • Alpha parameter controls transparency of the points

Conclusion

Creating 3D plots from numpy arrays involves extracting coordinate data and using Matplotlib's 3D plotting capabilities. Use nonzero() for sparse data or meshgrid coordinates for dense 3D visualizations.

Updated on: 2026-03-25T20:01:40+05:30

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements