0
0
Matplotlibdata~5 mins

Heatmap with plt.pcolormesh in Matplotlib

Choose your learning style9 modes available
Introduction

A heatmap shows how numbers change across two directions using colors.
Using plt.pcolormesh helps you draw this color grid easily.

You want to see how temperature changes across a map.
You want to compare sales numbers across different stores and months.
You want to visualize how a machine learning model's errors vary by two factors.
You want to quickly spot patterns or clusters in a table of numbers.
Syntax
Matplotlib
plt.pcolormesh(X, Y, C, shading='auto', cmap='viridis')
plt.colorbar()

X and Y are grid coordinates (can be 1D or 2D arrays).

C is the 2D array of values to color.

Examples
Basic heatmap with default X and Y coordinates.
Matplotlib
import numpy as np
import matplotlib.pyplot as plt

# Simple 2D data
C = np.array([[1, 2], [3, 4]])
plt.pcolormesh(C, shading='auto')
plt.colorbar()
plt.show()
Heatmap with explicit X and Y coordinates and a different color style.
Matplotlib
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(3)
y = np.arange(3)
C = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
plt.pcolormesh(x, y, C, shading='auto', cmap='plasma')
plt.colorbar()
plt.show()
Sample Program

This program creates a grid of points and calculates values using sine and cosine.
Then it draws a heatmap showing these values with colors.

Matplotlib
import numpy as np
import matplotlib.pyplot as plt

# Create data for heatmap
x = np.linspace(0, 5, 6)
y = np.linspace(0, 5, 6)
X, Y = np.meshgrid(x, y)

# Values: simple function of X and Y
C = np.sin(X) * np.cos(Y)

# Draw heatmap
plt.pcolormesh(X, Y, C, shading='auto', cmap='coolwarm')
plt.colorbar(label='Value')
plt.title('Heatmap with plt.pcolormesh')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
OutputSuccess
Important Notes

Use shading='auto' to avoid warnings about grid size.

The color map (cmap) changes the color style. Try different ones like viridis, plasma, or coolwarm.

Always add plt.colorbar() to explain what the colors mean.

Summary

Heatmaps show data values as colors on a grid.

plt.pcolormesh draws heatmaps using X, Y coordinates and values.

Adding a color bar helps understand the color scale.