← Back

Heatmap - Kernel Density Estimation

Summary

In this video I am going to show you how you can code heatmaps yourself and place them on any real world map you wish. I'll guide you through the math and how we can color each pixel. And here's the fun part. We are doing everything from scratch. So, no libraries, no frameworks, just pure coding.

Math

The heatmap intensity at each pixel is computed with kernel density estimation:

f^h(x)=1nhi=1nK(xxih)\hat{f}_h(x) = \frac{1}{n h} \sum_{i=1}^{n} K\left(\frac{x - x_i}{h}\right)

For this heatmap we use a bandwidth of h=2.5h = 2.5.

In code, using a Gaussian kernel, this looks like:

python
import numpy as np

def gaussian_kernel(u):
    return (1 / np.sqrt(2 * np.pi)) * np.exp(-0.5 * u**2)

def kde(x, data, h=2.5):
    n = len(data)
    return sum(gaussian_kernel((x - xi) / h) for xi in data) / (n * h)

GitHub

You can find the code here.