You spend hours analyzing tables with thousands of rows, trying to find patterns. A heatmap compresses that information onto a single screen: red zones are activity peaks, green zones are low activity. In two seconds, you see that orders most often happen on Friday evenings. But choosing the right stack is tricky: SVG lags on 10,000+ points, Canvas requires manual hit-testing, and backend integration can drag on. We solve this from scratch: from data preparation to production deployment. Our engineers use a modern stack: React, D3.js, Leaflet, Canvas — and integrate these solutions with your backend system. The result: you see patterns where tables require minutes of analysis.
What Problems Do We Solve?
A heatmap is a versatile tool, but it's important to choose the right visualization type. Let's examine four key variants.
Time-Based Activity
Rows — days of the week, columns — hours. Classic for showing when events occur (orders, visits, incidents). The GitHub contribution graph is exactly this type. It helps identify peak load hours and plan resources. Example: for an e-commerce store, we built a heatmap of activity by day and hour, which revealed a peak in orders at 8 PM on Fridays. After launching targeted push notifications, conversion increased by 15%.
Correlation Matrix
N×N cells, value from -1 to 1. Used in finance and ML to analyze dependencies between variables. For example, the relationship between ad spend and conversion.
Geographic Heatmap
Overlay point density on a map. Implemented via Leaflet + leaflet.heat or Mapbox. Useful for logistics, retail, foot traffic analysis.
Cohort Retention
Rows — cohorts (registration month), columns — retention periods. One of the key tools in product analytics. It shows how long users remain active after sign-up. We fix the color scale domain from 0 to 100% to avoid distortion.
Summary of heatmap types:
| Type | Data | Example Use |
|---|---|---|
| Time-based activity | (day, hour, count) | GitHub contribution graph |
| Correlation matrix | (variable, variable, coefficient) | Financial correlations |
| Geographic | (latitude, longitude, weight) | Customer distribution by location |
| Cohort retention | (cohort, period, %) | User retention after registration |
How to Choose Between SVG and Canvas?
Performance is the main criterion. D3.js documentation recommends Canvas for large datasets. An SVG heatmap of 10,000+ cells lags: each element is a separate DOM node. Canvas renders faster but requires manual hit-testing for tooltips. We choose the technology based on the task.
| Feature | SVG | Canvas |
|---|---|---|
| Cell count | up to 3,000 | 10,000+ |
| Tooltip | built-in | manual hit-test |
| Scaling | lossless | lossy |
| Development speed | faster | more complex |
For large volumes, we use Canvas. Example hit-testing:
useEffect(() => {
const canvas = canvasRef.current!;
const ctx = canvas.getContext('2d')!;
const dpr = window.devicePixelRatio;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
ctx.scale(dpr, dpr);
const cellW = iw / cols.length;
const cellH = ih / rows.length;
data.forEach(d => {
const x = margin.left + cols.indexOf(d.col) * cellW;
const y = margin.top + rows.indexOf(d.row) * cellH;
ctx.fillStyle = colorScale(d.value);
ctx.fillRect(x + 1, y + 1, cellW - 2, cellH - 2);
});
}, [data]);
Implementation with D3.js
import { useEffect, useRef } from 'react';
import * as d3 from 'd3';
interface HeatmapCell {
row: string;
col: string;
value: number;
}
interface HeatmapProps {
data: HeatmapCell[];
rows: string[];
cols: string[];
colorScheme?: 'blues' | 'reds' | 'greens' | 'rdylgn';
width?: number;
height?: number;
}
export function Heatmap({ data, rows, cols, colorScheme = 'blues', width = 700, height = 400 }: HeatmapProps) {
const svgRef = useRef<SVGSVGElement>(null);
const margin = { top: 30, right: 20, bottom: 60, left: 80 };
const iw = width - margin.left - margin.right;
const ih = height - margin.top - margin.bottom;
useEffect(() => {
if (!svgRef.current) return;
const svg = d3.select(svgRef.current);
svg.selectAll('*').remove();
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
const xScale = d3.scaleBand().domain(cols).range([0, iw]).padding(0.05);
const yScale = d3.scaleBand().domain(rows).range([0, ih]).padding(0.05);
const colorInterpolators = {
blues: d3.interpolateBlues,
reds: d3.interpolateReds,
greens: d3.interpolateGreens,
rdylgn: d3.interpolateRdYlGn,
};
const extent = d3.extent(data, d => d.value) as [number, number];
const colorScale = d3.scaleSequential()
.domain(extent)
.interpolator(colorInterpolators[colorScheme]);
// Axes
g.append('g')
.attr('transform', `translate(0,${ih})`)
.call(d3.axisBottom(xScale).tickSize(0))
.select('.domain').remove();
g.append('g')
.call(d3.axisLeft(yScale).tickSize(0))
.select('.domain').remove();
// Tooltip
const tooltip = d3.select('body').append('div')
.style('position', 'absolute')
.style('display', 'none')
.style('background', 'rgba(0,0,0,0.8)')
.style('color', '#fff')
.style('padding', '6px 10px')
.style('border-radius', '4px')
.style('font-size', '12px')
.style('pointer-events', 'none');
// Cells
g.selectAll('.cell')
.data(data)
.join('rect')
.attr('class', 'cell')
.attr('x', d => xScale(d.col)!)
.attr('y', d => yScale(d.row)!)
.attr('width', xScale.bandwidth())
.attr('height', yScale.bandwidth())
.attr('fill', d => d.value == null ? '#f0f0f0' : colorScale(d.value))
.attr('rx', 2)
.on('mouseover', (event, d) => {
tooltip
.style('display', 'block')
.style('left', `${event.pageX + 12}px`)
.style('top', `${event.pageY - 28}px`)
.html(`<strong>${d.row} / ${d.col}</strong><br/>${d3.format(',.2f')(d.value)}`);
})
.on('mouseout', () => tooltip.style('display', 'none'));
return () => { tooltip.remove(); };
}, [data, rows, cols, colorScheme]);
return <svg ref={svgRef} width={width} height={height} />;
}
Gradient Legend
function addColorLegend(
svg: d3.Selection<SVGSVGElement, unknown, null, undefined>,
colorScale: d3.ScaleSequential<string>,
x: number,
y: number,
width = 200,
height = 12
) {
const defs = svg.append('defs');
const gradientId = `legend-gradient-${Math.random().toString(36).slice(2)}`;
const gradient = defs.append('linearGradient').attr('id', gradientId);
gradient.append('stop').attr('offset', '0%').attr('stop-color', colorScale(colorScale.domain()[0]));
gradient.append('stop').attr('offset', '100%').attr('stop-color', colorScale(colorScale.domain()[1]));
const legendG = svg.append('g').attr('transform', `translate(${x},${y})`);
legendG.append('rect')
.attr('width', width)
.attr('height', height)
.style('fill', `url(#${gradientId})`);
const legendScale = d3.scaleLinear()
.domain(colorScale.domain())
.range([0, width]);
legendG.append('g')
.attr('transform', `translate(0,${height})`)
.call(d3.axisBottom(legendScale).ticks(4).tickFormat(d3.format(',.0f')));
}
Cohort Retention Heatmap
A special case with unique logic — values along the diagonal from 0% to 100%:
interface CohortRow {
cohort: string; // "Jan 2024"
periods: (number | null)[]; // retention % by period
}
function prepareCohortData(cohorts: CohortRow[]): HeatmapCell[] {
return cohorts.flatMap((row, rowIdx) =>
row.periods.map((value, colIdx) => ({
row: row.cohort,
col: `Period ${colIdx}`,
value: value ?? 0,
isEmpty: value === null,
}))
).filter(d => !d.isEmpty);
}
For retention, it's better to use d3.interpolateRdYlGn — red for low values, green for high. Fix the domain to [0, 100], not from min to max, otherwise the visualization misleads.
Why a Fixed Domain Matters
If the domain is dynamic, a difference between 80% and 90% will be shown vividly, even though both numbers are high. A fixed domain [0,100] gives an objective retention picture.
How to Integrate the Heatmap with Your API?
For large time ranges, data is aggregated on the server. We use PostgreSQL and Redis for caching, reducing API load. For example, for activity by day of week and hour, we use an SQL query:
SELECT
EXTRACT(DOW FROM created_at)::int AS dow,
EXTRACT(HOUR FROM created_at)::int AS hour,
COUNT(*) AS events
FROM user_events
WHERE created_at > NOW() - INTERVAL '90 days'
AND user_id = $1
GROUP BY 1, 2
ORDER BY 1, 2;
The result is passed via API, with empty cells filled with zeros on the server. We integrate with any backend: Laravel, Node.js, Python. If needed, we set up real-time updates via WebSocket.
What's Included?
- API documentation and architecture overview
- Source code with comments
- Adaptation to your CMS (WordPress, Drupal, Strapi)
- Maintenance instructions
- 1-month warranty on hidden defects
Timelines
Basic heatmap with tooltip and legend — 1–2 days. Cohort retention with proper data preparation — 3–5 days. Geographic heatmap — separate estimate. Pricing is individual.
Our company has over 5 years on the market and has delivered 30+ heatmap projects. Experience with Core Web Vitals ensures your heatmap won't slow down your site. Request a consultation — our engineers will analyze your data and propose the optimal solution. Contact us for a tailored estimate.







