How to display the matrix value and colormap in Matplotlib?

To display matrix values with a colormap in Matplotlib, you can use matshow() to create a color-coded visualization and overlay text annotations. This technique is useful for visualizing correlation matrices, confusion matrices, or any 2D data arrays.

Basic Matrix Display with Values

Here's how to create a matrix visualization with both colors and text values ?

import numpy as np
import matplotlib.pyplot as plt

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

# Create figure and subplot
fig, ax = plt.subplots()

# Create a sample matrix
min_val, max_val = 0, 5
matrix = np.random.randint(0, 5, size=(max_val, max_val))

# Display matrix as color-coded image
ax.matshow(matrix, cmap='ocean')

# Add text annotations for each cell
for i in range(max_val):
    for j in range(max_val):
        value = matrix[j, i]
        ax.text(i, j, str(value), va='center', ha='center', color='white')

plt.title('Matrix with Values and Colormap')
plt.show()

Customizing the Visualization

You can enhance the matrix display with better formatting and different colormaps ?

import numpy as np
import matplotlib.pyplot as plt

# Create a correlation-like matrix
data = np.array([[1.0, 0.8, 0.3, 0.1],
                 [0.8, 1.0, 0.5, 0.2],
                 [0.3, 0.5, 1.0, 0.7],
                 [0.1, 0.2, 0.7, 1.0]])

fig, ax = plt.subplots(figsize=(8, 6))

# Display with different colormap
im = ax.matshow(data, cmap='coolwarm', vmin=-1, vmax=1)

# Add colorbar
plt.colorbar(im, ax=ax, shrink=0.8)

# Add text annotations with formatting
for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        value = data[i, j]
        ax.text(j, i, f'{value:.2f}', 
                va='center', ha='center', 
                color='black', fontsize=12, fontweight='bold')

# Customize appearance
ax.set_title('Correlation Matrix', pad=20)
ax.set_xticks(range(4))
ax.set_yticks(range(4))
ax.set_xticklabels(['A', 'B', 'C', 'D'])
ax.set_yticklabels(['A', 'B', 'C', 'D'])

plt.tight_layout()
plt.show()

Key Parameters

Parameter Function Description
cmap matshow() Colormap for visualization
vmin, vmax matshow() Color scale limits
va, ha text() Vertical and horizontal alignment
color text() Text color

Common Colormaps

Different colormaps work better for different types of data ?

import numpy as np
import matplotlib.pyplot as plt

# Sample matrix
matrix = np.random.rand(4, 4)

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
colormaps = ['viridis', 'plasma', 'coolwarm']

for idx, cmap in enumerate(colormaps):
    ax = axes[idx]
    im = ax.matshow(matrix, cmap=cmap)
    
    # Add values
    for i in range(4):
        for j in range(4):
            ax.text(j, i, f'{matrix[i,j]:.2f}', 
                   va='center', ha='center', color='white')
    
    ax.set_title(f'Colormap: {cmap}')
    plt.colorbar(im, ax=ax, shrink=0.6)

plt.tight_layout()
plt.show()

Conclusion

Use matshow() to display matrices as color-coded images and text() to overlay values. Choose appropriate colormaps and text colors for better readability and visual appeal.

---
Updated on: 2026-03-26T00:07:11+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements