Construct a complete matrix and keep unmeasured cells separate from zero-valued measurements.
Heatmaps: make missing cells, rates and color domains explicit
A cell needs two keys and one measure
A heatmap is a matrix of marks whose position comes from two discrete dimensions and whose fill encodes a value. The first decision is the unit of a cell: one depot-day, one product-hour, or one model-class pair. Build the complete expected key grid before coloring it. Otherwise an absent record disappears, compresses the layout, or is mistaken for a low value. A white cell may mean zero, unobserved, unavailable or suppressed; these states require separate labels or patterns. Calendar completeness matters when columns are days.
Rates need their denominators
A defect-rate cell with 4 defects in 8 inspections and another with 40 in 800 inspections should not be interpreted as equally reliable even if their colors reflect 50% and 5%. Carry inspected count into a tooltip, visible annotation, or companion display. If no inspections occurred, the rate is undefined rather than zero. Measure grain determines whether the numerator and denominator belong to the same cell. If filters remove rows, recompute both counts instead of averaging precomputed cell percentages.
Fix the color domain for comparison
An automatically rescaled palette can make the same value change color when the viewer filters a subset. For cross-filter or before-after comparisons, set a stable domain and show its endpoints. A sequential palette fits a nonnegative rate; a diverging palette needs a meaningful center such as zero difference or target variance. Quantile coloring gives bins with similar record counts, not equal numeric widths. Label the bin rule. Accessible encodings add text or pattern cues so the chart still works without color.
Choose ordering deliberately
Alphabetical row order is reproducible, but ordering by a stable baseline can expose patterns. Clustering rows by similarity can reveal structure yet change the question: adjacent rows no longer imply geographic or operational proximity. If an algorithm orders rows, record its input period and freeze the order for comparisons. Keep hidden categories and totals visible. A truncated matrix that shows only the busiest depots is a selected population, not the entire network. Facet-order discipline applies here too.
Test the matrix contract
Include an observed zero, a missing key, a present key with zero exposure, an invalid negative count and a high-rate low-volume cell. Confirm each has a distinct state. Check the matrix against a long-form data table with the same row and column order. On mobile, provide axis labels that remain visible while scrolling; a distant legend is not enough. Exported CSV should retain status, numerator and denominator rather than only a color code.
Worked contract
def inspection_matrix(
observations: dict[tuple[str, str], tuple[int, int]],
depots: list[str], days: list[str]
) -> dict[tuple[str, str], tuple[str, float | None, int | None]]:
expected = {(depot, day) for depot in depots for day in days}
if len(expected) != len(depots) * len(days) or set(observations) - expected:
raise ValueError("duplicate labels or unexpected cell")
grid = {}
for key in expected:
if key not in observations:
grid[key] = ("missing", None, None)
continue
defects, inspected = observations[key]
if not 0 <= defects <= inspected:
raise ValueError("invalid cell counts")
grid[key] = ("no-exposure", None, 0) if inspected == 0 else (
"observed", defects / inspected, inspected)
return grid
matrix = inspection_matrix(
{("north", "Mon"): (0, 47), ("north", "Tue"): (0, 0)},
["north"], ["Mon", "Tue", "Wed"])
assert matrix[("north", "Mon")] == ("observed", 0.0, 47)
assert matrix[("north", "Tue")][0] == "no-exposure"
assert matrix[("north", "Wed")][0] == "missing"Performance and operating cost
For R row labels, C column labels and M supplied observations, building the expected grid takes O(RC + M) time and O(RC) space. Large sparse matrices should keep sparse storage and generate only visible tiles, but must still represent missing cells and axis positions correctly. The demonstration returns status, rate and denominator; a production export should also retain the numerator and source snapshot. Color scaling and rendering add work proportional to visible cells, not merely to supplied observations.
Common Mistakes
- Assigning the same white fill to an observed zero and an absent cell.
- Changing the color domain after filtering without warning the reader.
- Averaging cell percentages instead of recomputing counts for a new group.
- Sorting rows by one selected day, then describing the layout as a stable geographic order.
Validation drill
Build a depot-by-day inspection matrix with 6 depots and 17 days. Insert one missing cell, one zero-exposure cell and one observed zero. Verify their states in both chart legend and exported data.
Read next
- Aggregation grain and denominator: make every plotted mark auditable
- Accessible charts: encode meaning without relying on color alone
- Dense scatterplots: reveal overlap without hiding rare observations
- Dashboard filters and provenance: make every view reproducible
Continue this visualization path
- Correlation heatmaps: show pairwise coverage before interpreting color
- Calendar heatmaps: distinguish an empty day from an absent day
- Contour plots: respect measured grids and interpolation boundaries
- Confusion matrices: fix class order, denominators and abstentions
- Cohort retention heatmaps: keep immature cells blank
- Missingness matrices: reveal record-order patterns and co-missing fields
- Spectrograms: make time, frequency and color scales defensible
