data visualization
heatmap
scatter plot
data analysis
Python

Generate a heatmap using a scatter data set

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A scatter plot shows every point explicitly, which is useful until the plot becomes crowded. A heatmap solves that by converting point density into color, making clusters, sparse regions, and outliers easier to see at a glance.

The Simplest Approach: A 2D Histogram

The most direct way to turn scatter data into a heatmap is to bin the x and y values into a grid. Each grid cell counts how many points fall inside it, and the plotting library maps those counts to colors.

In Python, matplotlib.pyplot.hist2d does this with very little code:

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4rng = np.random.default_rng(42)
5x = np.concatenate([
6    rng.normal(loc=2.0, scale=0.6, size=1000),
7    rng.normal(loc=6.0, scale=0.8, size=1200),
8])
9y = np.concatenate([
10    rng.normal(loc=3.0, scale=0.7, size=1000),
11    rng.normal(loc=7.0, scale=1.0, size=1200),
12])
13
14plt.figure(figsize=(7, 5))
15plt.hist2d(x, y, bins=40, cmap="magma")
16plt.colorbar(label="Point count")
17plt.xlabel("x")
18plt.ylabel("y")
19plt.title("Heatmap from scatter data")
20plt.tight_layout()
21plt.show()

This example is fully runnable and produces a density-based heatmap from two clusters of scatter data.

Why a Heatmap Works Better Than a Dense Scatter Plot

If your dataset contains only a few dozen points, a scatter plot is usually enough. Once you move into hundreds or thousands of points, overplotting becomes a problem. Many points overlap, and the plot no longer communicates how dense each region really is.

A heatmap fixes that by aggregating nearby points. Instead of asking, "where is every point," you ask, "where are points concentrated?" That is often the more useful question for exploratory analysis.

The tradeoff is that you lose exact point positions. That is acceptable when the goal is density, not precise coordinates.

Choosing the Number of Bins

The bin count controls the resolution of the heatmap.

  • too few bins and different clusters get blurred together
  • too many bins and the image becomes noisy or sparse

A good starting point is between 30 and 60 bins on each axis for medium-sized datasets. Then adjust based on what you want to reveal.

You can also set separate counts for x and y:

python
plt.hist2d(x, y, bins=(50, 30), cmap="viridis")
plt.colorbar()
plt.show()

That is useful when the two axes cover different ranges or when one variable has naturally finer detail than the other.

Alternative: Hexagonal Binning

Square bins are easy to understand, but hexagons often produce a smoother visual result and reduce directional bias from the grid. Matplotlib includes hexbin for this purpose.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4rng = np.random.default_rng(0)
5x = rng.normal(size=3000)
6y = 0.5 * x + rng.normal(scale=0.7, size=3000)
7
8plt.figure(figsize=(7, 5))
9plt.hexbin(x, y, gridsize=35, cmap="plasma")
10plt.colorbar(label="Point count")
11plt.xlabel("x")
12plt.ylabel("y")
13plt.title("Hexbin heatmap")
14plt.tight_layout()
15plt.show()

This is still density visualization from scatter data, just with a different bin shape.

When to Use KDE Instead

If you want a smoother density estimate rather than bin counts, kernel density estimation, or KDE, is another option. It estimates a continuous density surface instead of discrete bins.

That can be visually attractive, but it introduces another tuning parameter called bandwidth. If you need a robust default, start with a 2D histogram or hexbin first. They are easier to explain and debug.

Common Pitfalls

A common mistake is forgetting the color bar. Without it, the viewer can see relative color changes but not what the colors represent.

Another mistake is using a bin count that is much too high for the sample size. That creates a blotchy image that looks like random noise rather than structure.

Developers also sometimes compare two heatmaps with different color scales and draw the wrong conclusion. If the purpose is comparison, keep the same colormap and value normalization.

Summary

  • Convert scatter data to a heatmap by binning points into a 2D grid.
  • 'plt.hist2d is the simplest runnable option in Matplotlib.'
  • Bin count controls the balance between smoothness and detail.
  • 'hexbin is a strong alternative when you want a cleaner density display.'
  • Use a color bar and consistent scaling so the heatmap communicates actual density.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.