How to apply a mask on the matrix in Matplotlib imshow?

To apply a mask on a matrix in Matplotlib imshow(), we can use np.ma.masked_where() method to hide specific values based on conditions. This is useful for highlighting data ranges or removing unwanted values from visualization.

What is Matrix Masking?

Matrix masking allows you to selectively hide or highlight certain values in your data visualization. Masked values appear transparent or use different colors, making it easier to focus on specific data ranges.

Example: Masking Values Within a Range

Let's create a visualization that masks values between lower and upper thresholds ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True

# Define mask thresholds
lower = 0.3
upper = 0.7

# Create sample data
data = np.random.rand(5, 5)
print("Original data:")
print(data)

# Apply mask to hide values between lower and upper thresholds
masked_data = np.ma.masked_where((lower < data) & (data < upper), data)

# Create side-by-side comparison
fig, axs = plt.subplots(1, 2)

# Original data
axs[0].imshow(data, cmap='viridis')
axs[0].set_title("Original Data")

# Masked data
axs[1].imshow(masked_data, cmap='viridis')
axs[1].set_title("Masked Data (0.3 < value < 0.7 hidden)")

plt.show()

Different Masking Conditions

You can apply various masking conditions based on your needs ?

import numpy as np
import matplotlib.pyplot as plt

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

fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# Original data
axs[0,0].imshow(data, cmap='coolwarm')
axs[0,0].set_title("Original Data")

# Mask values greater than 0.6
mask1 = np.ma.masked_where(data > 0.6, data)
axs[0,1].imshow(mask1, cmap='coolwarm')
axs[0,1].set_title("Values > 0.6 Masked")

# Mask values less than 0.4
mask2 = np.ma.masked_where(data < 0.4, data)
axs[1,0].imshow(mask2, cmap='coolwarm')
axs[1,0].set_title("Values < 0.4 Masked")

# Mask values outside range [0.3, 0.7]
mask3 = np.ma.masked_where((data < 0.3) | (data > 0.7), data)
axs[1,1].imshow(mask3, cmap='coolwarm')
axs[1,1].set_title("Values Outside [0.3, 0.7] Masked")

plt.tight_layout()
plt.show()

Key Parameters

Function Purpose Usage
np.ma.masked_where() Mask array elements meeting condition masked_where(condition, array)
cmap Colormap for visualization imshow(data, cmap='viridis')
alpha Transparency of masked areas imshow(data, alpha=0.8)

Conclusion

Use np.ma.masked_where() with logical conditions to selectively hide matrix values in imshow(). This technique is powerful for data analysis and creating focused visualizations by removing noise or highlighting specific value ranges.

Updated on: 2026-03-25T23:59:29+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements