0
0
Matplotlibdata~5 mins

Heatmap with plt.imshow in Matplotlib

Choose your learning style9 modes available
Introduction

A heatmap helps you see patterns in numbers by showing colors for values in a grid.

To quickly see how values change across a table of numbers.
To compare data like temperatures or scores in different places.
To find areas with high or low values in a matrix.
To visualize correlations or relationships in data.
To show intensity or frequency in a simple color map.
Syntax
Matplotlib
plt.imshow(data, cmap='color_map_name', interpolation='method')
plt.colorbar()
plt.show()

data is a 2D array or matrix of numbers.

cmap sets the color style, like 'viridis' or 'hot'.

Examples
Basic heatmap with default colors and interpolation.
Matplotlib
plt.imshow(data)
plt.colorbar()
plt.show()
Heatmap with warm colors from black to red to yellow.
Matplotlib
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.show()
Heatmap with cool colors and no smoothing between pixels.
Matplotlib
plt.imshow(data, cmap='cool', interpolation='nearest')
plt.colorbar()
plt.show()
Sample Program

This code makes a simple 5 by 5 grid of numbers from 0 to 24. Then it shows a heatmap using the 'viridis' colors. The color bar on the side helps understand the values by color.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create a 5x5 matrix with values from 0 to 24
data = np.arange(25).reshape(5, 5)

# Show heatmap with 'viridis' color map
plt.imshow(data, cmap='viridis')
plt.colorbar()  # Show color scale
plt.title('Heatmap with plt.imshow')
plt.show()
OutputSuccess
Important Notes

Use plt.colorbar() to add a color scale next to the heatmap.

Try different cmap values to find colors that suit your data.

interpolation='nearest' shows sharp blocks, while default smooths colors.

Summary

Heatmaps show data values as colors in a grid.

plt.imshow() is an easy way to create heatmaps in matplotlib.

Adding a color bar helps read the values from colors.