How can I display an np.array with pylab.imshow() using Matplotlib?

To display a NumPy array as an image using Matplotlib's imshow() function, you need to create a 2D array and use the appropriate display parameters. The imshow() function treats each array element as a pixel value and maps it to colors based on the specified colormap.

Basic Steps

  • Create a 2D NumPy array containing your data
  • Use plt.imshow() to display the array as an image
  • Specify interpolation method and colormap for better visualization
  • Display the figure using plt.show()

Example

import numpy as np
import matplotlib.pyplot as plt

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

# Create a 2D NumPy array
data = np.array([
    [0.1, 0.7, 0.6, 0.3],
    [0.2, 0.6, 0.5, 0.2],
    [0.8, 0.3, 0.8, 0.01],
    [0.3, 0.4, 0.2, 0.1]
])

# Display the array as an image
plt.imshow(data, interpolation="nearest", cmap="RdYlGn_r")
plt.colorbar()  # Add colorbar to show value mapping
plt.title("NumPy Array Visualization")
plt.show()

Key Parameters

  • interpolation: Controls how pixel values are interpolated. "nearest" shows exact values without smoothing
  • cmap: Colormap for mapping values to colors. "RdYlGn_r" goes from red (low) to green (high)
  • aspect: Controls the aspect ratio of the image (default is "equal")

Different Colormaps Example

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = np.random.rand(5, 5)

# Display with different colormaps
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].imshow(data, cmap='viridis')
axes[0].set_title('Viridis Colormap')

axes[1].imshow(data, cmap='plasma')
axes[1].set_title('Plasma Colormap')

axes[2].imshow(data, cmap='gray')
axes[2].set_title('Grayscale')

plt.tight_layout()
plt.show()

Conclusion

Use plt.imshow() to display NumPy arrays as images with customizable colormaps and interpolation. Add plt.colorbar() to show the value-to-color mapping for better interpretation of your data visualization.

---
Updated on: 2026-03-25T21:26:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements