Skip to content

Commit 55bc9f3

Browse files
authored
Heatmaps plus (#3427)
This change adds color scaling controls, motivated by some in-house feedback as well as a great [blog entry](https://www.davepacheco.net/blog/2011/heatmap-coloring/) from Dave on the benefits of ranked coloring in particular. This expands out to a wider introduction of a settings button for the page, because "Drop first data point" was esoteric enough; the coloring scheme, in my opinion, should not be a concern for a first-time viewer, and potentially never a concern. Plus, pushing it off to a popover gives us some wiggle room to really be descriptive for users who do want to weigh their options when picking a color scheme. https://github.com/user-attachments/assets/0907edaf-6ab8-4bf5-864f-1bb055e3b896
1 parent 3740319 commit 55bc9f3

6 files changed

Lines changed: 455 additions & 69 deletions

File tree

‎app/components/Heatmap.tsx‎

Lines changed: 107 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,16 @@
77
*/
88
import { useMemo, useState } from 'react'
99
import * as R from 'remeda'
10+
import { match } from 'ts-pattern'
1011
import type uPlot from 'uplot'
1112

1213
import { ChartTooltip, type TopBottom, type LeftRight } from '~/components/ChartTooltip'
1314
import { type UPlotOptions, FramedChart } from '~/components/FramedChart'
15+
import {
16+
getSampleCountMetadata,
17+
getScalingFunction,
18+
type ColorScale,
19+
} from '~/components/heatmap-color-scale'
1420
import {
1521
timeFormatterForRange,
1622
useChartTheme,
@@ -40,38 +46,20 @@ const RAMP_STOPS = [
4046
['--content-accent', 'oklch(0.77 0.1919 163.7)'],
4147
] as const
4248

49+
const CSS_VAR_RAMP: ColorRamp = {
50+
stops: RAMP_STOPS.map(([name, fallback]) => `var(${name}, ${fallback})`),
51+
}
52+
4353
// Interpolates the color between the two closest stops, for 0 <= t <= 1.
4454
const rampColor = ({ stops }: ColorRamp, t: number): string => {
4555
const clamped = R.clamp(t, { min: 0, max: 1 })
4656
const lastIndex = stops.length - 1
4757
const progress = clamped * lastIndex
4858
const start = R.clamp(Math.floor(progress), { max: lastIndex - 1 })
49-
const lerp = progress - start
59+
const localT = progress - start
5060
const from = stops[start]
5161
const to = stops[start + 1]
52-
return `color-mix(in oklch, ${from} ${(1 - lerp) * 100}%, ${to})`
53-
}
54-
55-
// grabbing style from the chart root instead of document body
56-
// that way it can be themed e.g. `yellow-theme`
57-
const getColorRamp = (el: Element): ColorRamp => {
58-
const style = getComputedStyle(el)
59-
return {
60-
stops: RAMP_STOPS.map(
61-
([name, fallback]) => style.getPropertyValue(name).trim() || fallback
62-
),
63-
}
64-
}
65-
66-
// count -> ramp position. Doing a square root or a log makes for some different
67-
// smoothing. Nothing is truly intuitive, but linearly showing the fraction is
68-
// most easily compared to the legend at the bottom
69-
const rampT = (count: number, maxCount: number) => {
70-
const fraction = count / maxCount
71-
// TODO: pick!
72-
return fraction
73-
// return Math.log10(lerp(1, 10, fraction))
74-
// return Math.sqrt(fraction)
62+
return `color-mix(in oklch, ${from}, ${to} ${localT * 100}%)`
7563
}
7664

7765
type Hover = {
@@ -93,6 +81,7 @@ type HeatmapProps = {
9381
unit?: string
9482
/** Drawn rotated alongside the y-axis tick labels, e.g. a unit */
9583
yAxisLabel?: string
84+
colorScale?: ColorScale
9685
}
9786

9887
const defaultYAxisTickFormatter = (val: number) => val.toLocaleString()
@@ -105,6 +94,7 @@ export function Heatmap({
10594
yAxisTickFormatter = defaultYAxisTickFormatter,
10695
unit,
10796
yAxisLabel,
97+
colorScale = 'ranked',
10898
}: HeatmapProps) {
10999
const theme = useChartTheme()
110100
const [hover, setHover] = useState<Hover | null>(null)
@@ -118,8 +108,8 @@ export function Heatmap({
118108
const binCount = bins.length
119109
const colCount = distributions.length
120110

121-
const maxSampleCount = useMemo(
122-
() => distributions.reduce((max, d) => (d ? Math.max(max, ...d.counts) : max), 0),
111+
const sampleCountMetadata = useMemo(
112+
() => getSampleCountMetadata(distributions.flatMap((d) => d?.counts ?? [])),
123113
[distributions]
124114
)
125115

@@ -129,10 +119,22 @@ export function Heatmap({
129119

130120
// uPlot doesn't actually have heatmap support, but we can use its position
131121
// functions to make this (somewhat) easy
132-
const drawCells = useMemo(
133-
() => (u: uPlot) => {
122+
const drawCells = useMemo(() => {
123+
const scaleCount = getScalingFunction(sampleCountMetadata, colorScale)
124+
125+
return (u: uPlot) => {
134126
if (binCount === 0 || colCount === 0) return
135-
const colorRamp = getColorRamp(u.root)
127+
128+
// since a canvas can't resolve CSS variables, we simulate it by reading
129+
// the ramp colors off the element furthest down the tree (the chart's
130+
// root element)
131+
const style = getComputedStyle(u.root)
132+
const colorRamp = {
133+
stops: RAMP_STOPS.map(
134+
([name, fallback]) => style.getPropertyValue(name).trim() || fallback
135+
),
136+
}
137+
136138
const ctx = u.ctx
137139
ctx.save()
138140
ctx.beginPath()
@@ -149,7 +151,7 @@ export function Heatmap({
149151

150152
const topEdge = u.valToPos(rowIndex + 1, 'y', true)
151153
const bottomEdge = u.valToPos(rowIndex, 'y', true)
152-
ctx.fillStyle = rampColor(colorRamp, rampT(count, maxSampleCount))
154+
ctx.fillStyle = rampColor(colorRamp, scaleCount(count))
153155
ctx.fillRect(
154156
leftEdge - CELL_OVERFLOW,
155157
topEdge - CELL_OVERFLOW,
@@ -159,9 +161,16 @@ export function Heatmap({
159161
})
160162
})
161163
ctx.restore()
162-
},
163-
[distributions, leftEdges, rightEdges, colCount, binCount, maxSampleCount]
164-
)
164+
}
165+
}, [
166+
distributions,
167+
leftEdges,
168+
rightEdges,
169+
colCount,
170+
binCount,
171+
colorScale,
172+
sampleCountMetadata,
173+
])
165174

166175
const tooltipPlugin = useMemo<uPlot.Plugin>(
167176
() => ({
@@ -307,7 +316,19 @@ export function Heatmap({
307316
chartOptions={chartOptions}
308317
data={data}
309318
uRef={uRef}
310-
legend={<HeatmapLegend maxSampleCount={maxSampleCount} axisText={theme.axisText} />}
319+
legend={
320+
sampleCountMetadata.ranks.size > 0 && (
321+
<HeatmapLegend
322+
minSampleCount={match(colorScale)
323+
.with('ranked', () => sampleCountMetadata.minSampleCount)
324+
.with('linear', () => 0)
325+
.with('logarithmic', () => 1)
326+
.exhaustive()}
327+
maxSampleCount={sampleCountMetadata.maxSampleCount}
328+
axisText={theme.axisText}
329+
/>
330+
)
331+
}
311332
>
312333
{hover && (
313334
<>
@@ -342,28 +363,69 @@ export function Heatmap({
342363
}
343364

344365
function HeatmapLegend({
366+
minSampleCount,
345367
maxSampleCount,
346368
axisText,
347369
}: {
370+
minSampleCount: number
348371
maxSampleCount: number
349372
axisText: string
350373
}) {
351374
return (
352375
<div className="mt-3 flex items-center gap-2 pl-5">
353-
<span className="text-mono-xs" style={{ color: axisText }}>
354-
0
355-
</span>
356-
<div
357-
className="h-3 w-32 rounded-sm"
358-
style={{
359-
backgroundImage: `linear-gradient(in oklch to right, ${RAMP_STOPS.map(
360-
([name, fallback]) => `var(${name}, ${fallback})`
361-
).join(', ')})`,
362-
}}
363-
></div>
376+
{minSampleCount === maxSampleCount ? (
377+
<div
378+
className="h-3 w-3 rounded-sm"
379+
style={{
380+
backgroundColor: R.last(CSS_VAR_RAMP.stops),
381+
}}
382+
></div>
383+
) : (
384+
<>
385+
<span className="text-mono-xs" style={{ color: axisText }}>
386+
{minSampleCount.toLocaleString()}
387+
</span>
388+
<div
389+
className="h-3 w-32 rounded-sm"
390+
style={{
391+
backgroundImage: `linear-gradient(in oklch to right, ${CSS_VAR_RAMP.stops.join(', ')})`,
392+
}}
393+
></div>
394+
</>
395+
)}
364396
<span className="text-mono-xs" style={{ color: axisText }}>
365397
{maxSampleCount.toLocaleString()}
366398
</span>
367399
</div>
368400
)
369401
}
402+
403+
const SAMPLE_VALUES = [1, 5, 10, 50, 95, 100]
404+
const SAMPLE_VALUES_METADATA = getSampleCountMetadata(SAMPLE_VALUES)
405+
const LONGEST_SAMPLE_ITEM = SAMPLE_VALUES.map((n) => n.toLocaleString().length).reduce(
406+
(acc, length) => Math.max(acc, length),
407+
0
408+
)
409+
410+
export function SampleColorStrip({ colorScale }: { colorScale: ColorScale }) {
411+
const scaleCount = getScalingFunction(SAMPLE_VALUES_METADATA, colorScale)
412+
413+
return (
414+
<div className="flex items-end gap-px">
415+
{SAMPLE_VALUES.map((n) => (
416+
<div
417+
key={n}
418+
className="text-secondary text-mono-code flex flex-col items-center text-xs"
419+
>
420+
<div className="text-center" style={{ width: `${LONGEST_SAMPLE_ITEM + 0.5}ch` }}>
421+
{n.toLocaleString()}
422+
</div>
423+
<div
424+
className="h-3 w-full"
425+
style={{ backgroundColor: rampColor(CSS_VAR_RAMP, scaleCount(n)) }}
426+
/>
427+
</div>
428+
))}
429+
</div>
430+
)
431+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import { describe, expect, it } from 'vitest'
9+
10+
import {
11+
getSampleCountMetadata,
12+
getScalingFunction,
13+
type ColorScale,
14+
} from './heatmap-color-scale'
15+
16+
const scale = (counts: number[], colorScale: ColorScale) =>
17+
getScalingFunction(getSampleCountMetadata(counts), colorScale)
18+
19+
describe('getSampleCountMetadata', () => {
20+
it('ignores zeros and duplicates', () => {
21+
const { minSampleCount, maxSampleCount, ranks } = getSampleCountMetadata([
22+
50, 0, 5, 50, 0, 100,
23+
])
24+
expect(minSampleCount).toBe(5)
25+
expect(maxSampleCount).toBe(100)
26+
expect([...ranks]).toEqual([
27+
[5, 0],
28+
[50, 1],
29+
[100, 2],
30+
])
31+
})
32+
33+
it('handles lack of samples', () => {
34+
const { minSampleCount, maxSampleCount, ranks } = getSampleCountMetadata([0, 0])
35+
expect(minSampleCount).toBe(0)
36+
expect(maxSampleCount).toBe(0)
37+
expect(ranks.size).toBe(0)
38+
})
39+
})
40+
41+
describe('linear', () => {
42+
it('is the fraction of the max', () => {
43+
const f = scale([10, 50, 200], 'linear')
44+
expect(f(10)).toBe(0.05)
45+
expect(f(50)).toBe(0.25)
46+
expect(f(200)).toBe(1)
47+
})
48+
})
49+
50+
describe('logarithmic', () => {
51+
it("has 1 as 0 and the collection's greatest value as 1", () => {
52+
const f = scale([10, 200], 'logarithmic')
53+
expect(f(1)).toBe(0)
54+
expect(f(200)).toBe(1)
55+
})
56+
57+
it('gives equal ratios equal steps', () => {
58+
const expectEqualSpacing = (values: number[]) => {
59+
const f = scale(values, 'logarithmic')
60+
values.forEach((value, i) => expect(f(value)).toBeCloseTo(i / (values.length - 1)))
61+
}
62+
63+
expectEqualSpacing([1, 10, 100, 1000, 10000])
64+
expectEqualSpacing([1, 7, 49, 343])
65+
})
66+
67+
it("makes an exception when the collection's greatest value is 1", () => {
68+
expect(scale([1, 0], 'logarithmic')(1)).toBe(1)
69+
})
70+
})
71+
72+
describe('ranked', () => {
73+
it('spaces distinct counts evenly', () => {
74+
const f = scale([1, 2, 1000], 'ranked')
75+
expect(f(1)).toBe(0)
76+
expect(f(2)).toBe(0.5)
77+
expect(f(1000)).toBe(1)
78+
})
79+
80+
it('ignores duplicates', () => {
81+
const f = scale([3, 3, 7, 9], 'ranked')
82+
expect(f(3)).toBe(0)
83+
expect(f(7)).toBe(0.5)
84+
})
85+
86+
it('puts a single count at the top', () => {
87+
expect(scale([4, 4, 0], 'ranked')(4)).toBe(1)
88+
})
89+
})
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import * as R from 'remeda'
9+
import { match } from 'ts-pattern'
10+
11+
export type ColorScale = 'linear' | 'logarithmic' | 'ranked'
12+
13+
const scaleLinear =
14+
(maxCount: number) =>
15+
(count: number): number =>
16+
count / maxCount
17+
const scaleLog = (maxCount: number) =>
18+
maxCount <= 1
19+
? // if the max is 1, a logarithmic scaling function is undefined. but
20+
// since 1 is then the only valid value, in a charting context it makes
21+
// sense to treat that as a scale of 100%
22+
R.constant(1)
23+
: (count: number): number => Math.log(count) / Math.log(maxCount)
24+
const scaleRank = (ranks: Map<number, number>) =>
25+
ranks.size <= 1
26+
? R.constant(1)
27+
: (count: number): number => (ranks.get(count) ?? 0) / (ranks.size - 1)
28+
29+
export type SampleCountMetadata = {
30+
minSampleCount: number
31+
maxSampleCount: number
32+
ranks: Map<number, number>
33+
}
34+
35+
export const getSampleCountMetadata = (counts: number[]): SampleCountMetadata => {
36+
const allCounts = R.sort(
37+
R.unique(counts).filter((x) => x !== 0),
38+
(a, b) => a - b
39+
)
40+
41+
return {
42+
minSampleCount: R.first(allCounts) ?? 0,
43+
maxSampleCount: R.last(allCounts) ?? 0,
44+
ranks: new Map(allCounts.map((n, i) => [n, i])),
45+
}
46+
}
47+
48+
/**
49+
* Maps a sample count to a position for a color ramp, from 0 to 1.
50+
* Expects that the count given to the final scaling function is a nonzero
51+
* natural number.
52+
*/
53+
export const getScalingFunction = (
54+
metadata: SampleCountMetadata,
55+
colorScale: ColorScale
56+
): ((n: number) => number) =>
57+
match(colorScale)
58+
.with('linear', () => scaleLinear(metadata.maxSampleCount))
59+
.with('logarithmic', () => scaleLog(metadata.maxSampleCount))
60+
.with('ranked', () => scaleRank(metadata.ranks))
61+
.exhaustive()

0 commit comments

Comments
 (0)