Displaying a 3D Tensor with Matplotlib
Here's a Python code example that demonstrates how to visualize a 3D tensor (3-dimensional array) using matplotlib. Since matplotlib is primarily designed for 2D plotting, we'll need to create multiple 2D slices or use 3D plotting techniques to represent the tensor.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def display_3d_tensor(tensor, title="3D Tensor Visualization"):
"""
Visualize a 3D tensor using matplotlib.
Parameters:
- tensor: 3D numpy array to visualize
- title: Title for the plot
"""
# Check if the input is a 3D tensor
if tensor.ndim != 3:
raise ValueError("Input must be a 3D tensor")
depth, height, width = tensor.shape
# Create a figure
plt.figure(figsize=(12, 8))
plt.suptitle(title, y=1.02)
# Method 1: Show slices along the first dimension
plt.subplot(1, 2, 1)
plt.title("Slices along first dimension")
# Show a few representative slices
num_slices = min(5, depth)
for i in range(num_slices):
slice_idx = i * (depth // num_slices)
plt.imshow(tensor[slice_idx], cmap='viridis', alpha=0.7)
plt.text(0.5, 0.95, f"Slice {slice_idx}",
transform=plt.gca().transAxes,
ha='center', va='top', color='white')
plt.show(block=False)
plt.pause(0.5)
plt.clf()
# Method 2: 3D voxel plot (for smaller tensors)
if depth * height * width <= 10000: # Limit for performance
plt.subplot(1, 2, 2)
ax = plt.gca(projection='3d')
# Create a grid of coordinates
x, y, z = np.indices(tensor.shape)
colors = tensor.flatten() / tensor.max() # Normalize for coloring
# Plot voxels
ax.voxels(x, y, z, tensor, facecolors=plt.cm.viridis(colors), edgecolor='k')
ax.set_title("3D Voxel Representation")
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.tight_layout()
plt.show()
# Example usage
if __name__ == "__main__":
# Create a sample 3D tensor (10x10x10)
tensor = np.random.rand(10, 10, 10)
# Add some structure to make it more interesting
tensor[2:5, 3:7, 4:8] = 0.8
tensor[6:9, 1:4, 5:9] = 0.2
display_3d_tensor(tensor, "Sample 3D Tensor Visualization")
Alternative Visualization Methods
For larger tensors or different visualization needs, you might want to consider these alternatives:
- Heatmap slices:
def plot_heatmap_slices(tensor):
"""Plot heatmaps of slices along the first dimension"""
fig, axes = plt.subplots(1, min(5, tensor.shape[0]), figsize=(15, 3))
for i, ax in enumerate(axes):
slice_idx = i * (tensor.shape[0] // len(axes))
im = ax.imshow(tensor[slice_idx], cmap='viridis')
ax.set_title(f"Slice {slice_idx}")
fig.colorbar(im, ax=ax)
plt.tight_layout()
plt.show()
- Projection views:
def plot_projections(tensor):
"""Plot max projections along each axis"""
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].imshow(tensor.max(axis=0), cmap='viridis')
axes[0].set_title("Max projection along axis 0")
axes[1].imshow(tensor.max(axis=1), cmap='viridis')
axes[1].set_title("Max projection along axis 1")
axes[2].imshow(tensor.max(axis=2), cmap='viridis')
axes[2].set_title("Max projection along axis 2")
plt.tight_layout()
plt.show()