Guides
Thresholds
A threshold turns a number into a category: a page load of 3.1 s is "Needs improvement", a margin of 9% is "Critical". thresholds() builds those categories once, and the same result colors a ZoneMeter, counts a Legend and tones the dots of a DotHistogram, so a value gets the same color everywhere. heatmapLevel() does the matching job for a Heatmap.
Building thresholds #
thresholds(breaks, tones, labels, options) takes the ascending break values, a tone for each bin and a label for each bin. There is one more tone and one more label than there are breaks: two breaks make three bins. A spec that does not fit, or breaks that are not finite and strictly ascending, throws, because it is a mistake in the code rather than in the data.
import { thresholds } from 'tally-charts'
// Largest contentful paint in seconds: 2 breaks, 3 bins.
const lcp = thresholds(
[2.5, 4],
['gain', 'warn', 'loss'],
['Good', 'Needs improvement', 'Poor'],
)
lcp.indexOf(3.1) // 1
lcp.toneOf(3.1) // 'warn'
lcp.toneOf('n/a') // undefined
lcp.indexOf('n/a') // -1The result carries the plain data and three helpers. bins lists the bins as { label, tone, min, max }; the first starts at -Infinity and the last ends at Infinity. indexOf(value) is the index of the bin that holds a value, or -1 for a value that is missing or not a number. toneOf(value) is the tone of that bin. legend(values) counts how many of the values fall into each bin and returns entries for a Legend.
Which bin holds a value on a break #
The inclusive option decides what happens to a value that is exactly on a break. With 'lower', the default, a bin is [min, max): the value belongs to the bin above the break. With 'upper' a bin is (min, max]: the value belongs to the bin below it, which is how Core Web Vitals count their tiers.
Take an LCP of exactly 2.5 s against the breaks [2.5, 4]. With inclusive: 'lower' it is "Needs improvement", because 2.5 starts the second bin. With inclusive: 'upper' it is "Good", because 2.5 ends the first one. The same goes for 4 s: "Poor" with 'lower', "Needs improvement" with 'upper'. Values that are not on a break fall in the same bin either way.
const strict = thresholds([2.5, 4], tones, labels) // 'lower'
const vitals = thresholds([2.5, 4], tones, labels, { inclusive: 'upper' })
strict.toneOf(2.5) // 'warn' (Needs improvement)
vitals.toneOf(2.5) // 'gain' (Good)In ZoneMeter, Legend and DotHistogram #
Pass the result to ZoneMeter as zones: the track draws one zone per bin and the marker sits at the value, which the screen reader hears together with the label of its bin. ZoneMeter reads inclusive too, so a value on a break lands in the bin your thresholds() call says. Pass it to DotHistogram as toneBy to tone each dot by its bin, and give Legend the result of legend(values) with shape="dot" for the swatches and counts.
- Good13
- Needs improvement7
- Poor3
| Item | Lcp | Group |
|---|---|---|
| no value | 1.2 | Good |
| no value | 1.4 | Good |
| no value | 1.5 | Good |
| no value | 1.7 | Good |
| no value | 1.8 | Good |
| no value | 1.9 | Good |
| no value | 2 | Good |
| no value | 2.1 | Good |
| no value | 2.2 | Good |
| no value | 2.3 | Good |
| no value | 2.4 | Good |
| no value | 2.5 | Good |
| no value | 2.5 | Good |
| no value | 2.6 | Needs improvement |
| no value | 2.8 | Needs improvement |
| no value | 3 | Needs improvement |
| no value | 3.2 | Needs improvement |
| no value | 3.5 | Needs improvement |
| no value | 3.8 | Needs improvement |
| no value | 4 | Needs improvement |
| no value | 4.3 | Poor |
| no value | 4.8 | Poor |
| no value | 5.4 | Poor |
'use client'
import { DotHistogram, Legend, thresholds, ZoneMeter } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'thresholds/zones-and-dots',
title: 'Page loads by largest contentful paint, colored by tier',
rscSafe: false,
} satisfies ExampleMeta
// Core Web Vitals tiers for LCP in seconds: breaks 2.5 and 4, one more tone and label than breaks.
const tones = ['gain', 'warn', 'loss'] as const
const labels = ['Good', 'Needs improvement', 'Poor']
// 'upper' counts a value on a break in the bin below it, as Core Web Vitals do.
const tiers = thresholds([2.5, 4], tones, labels, { inclusive: 'upper' })
// The default, 'lower': a value on a break falls in the bin above it.
const strict = thresholds([2.5, 4], tones, labels)
const loads = [
1.2, 1.4, 1.5, 1.7, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.5, 2.6, 2.8, 3, 3.2, 3.5, 3.8, 4, 4.3,
4.8, 5.4,
].map((lcp, i) => ({ id: `load-${i + 1}`, lcp }))
const grid = {
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 16rem), 1fr))',
gap: '1.5rem',
} as const
// 'use client': a thresholds() result has methods, so it can't be passed from a Server Component
// to a chart as `toneBy`. ZoneMeter alone could take the plain `{ bins, inclusive }` instead.
export default function ZonesAndDots() {
return (
<div style={{ display: 'grid', gap: '1.75rem' }}>
<div style={grid}>
<ZoneMeter
label="LCP of 2.5 s, inclusive upper"
value={2.5}
zones={tiers}
max={6}
maxLabel="6 s+"
format={{ preset: 'number', digits: 1 }}
/>
<ZoneMeter
label="LCP of 2.5 s, inclusive lower"
value={2.5}
zones={strict}
max={6}
maxLabel="6 s+"
format={{ preset: 'number', digits: 1 }}
/>
</div>
<Legend shape="dot" items={tiers.legend(loads.map((l) => l.lcp))} />
<DotHistogram
title={meta.title}
description="Of 23 page loads, 13 are Good, 7 need improvement and 3 are Poor. The two loads of exactly 2.5 s count as Good."
data={loads}
value="lcp"
id="id"
toneBy={tiers}
binWidth={0.25}
domain={[0, 6]}
format={{ preset: 'number', digits: 1 }}
height={220}
/>
</div>
)
}
Both meters show the same value, 2.5 s. The first uses inclusive: 'upper' and reads "Good"; the second uses the default and reads "Needs improvement". The two loads of exactly 2.5 s in the histogram are toned and counted as Good. The thresholds() result has methods, so it can only be passed from a client component. A Server Component can give ZoneMeter the plain { bins, inclusive } instead; see Server Components.
Parameters of thresholds #
| Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
breaks | readonly number[] | — | Yes | — |
tones | readonly Tone[] | — | Yes | — |
labels | readonly string[] | — | Yes | — |
options | ThresholdOptions | {} | No | — |
Returns Thresholds
Matching a Heatmap #
A Heatmap bins its values by breaks and paints each cell with a sequential level from 1 to 5. Its own legend already matches. When you draw the legend yourself, with a standalone Legend somewhere else on the page, heatmapLevel(value, breaks) gives the level the heatmap would paint that value with, so the swatches use the same colors. It returns 0 for a missing or non-numeric value.
The breaks are cleaned the way Heatmap cleans them: sorted, deduplicated and cut to the first four, which make the five bins. Four bins use the levels 1, 2, 4 and 5, and fewer bins spread over the range with the ends pinned, so do not work the levels out by hand. Take one value from each bin, ask heatmapLevel for its level and set it as the level of a Legend item. These are plain numbers, so the call also works in a Server Component.
import { BarChart, Heatmap, Legend } from 'tally-charts'
import { heatmapLevel } from 'tally-charts/core'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'thresholds/heatmap-legend',
title: 'Support tickets by day and category, with a legend of the same bins',
rscSafe: true,
} satisfies ExampleMeta
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
const tickets: Record<string, number[]> = {
Billing: [12, 18, 9, 22, 31],
Login: [41, 36, 28, 33, 19],
Shipping: [5, 8, 14, 11, 7],
}
const data = Object.entries(tickets).flatMap(([category, counts]) =>
counts.map((count, i) => ({ category, day: days[i] ?? '', count })),
)
const perDay = days.map((day, i) => ({
day,
count: Object.values(tickets).reduce((sum, counts) => sum + (counts[i] ?? 0), 0),
}))
// The breaks and the labels of the five bins; the Heatmap and the Legend both read them.
const breaks = [10, 20, 30, 40]
const labels = ['Under 10', '10 to 20', '20 to 30', '30 to 40', '40 and up']
// One value inside each bin: heatmapLevel gives the level the Heatmap paints it with, so the
// swatches match. Plain numbers, so this runs on the server.
const samples = [5, 15, 25, 35, 45]
// Props stay serializable (no functions): the page is a server component.
export default function HeatmapLegend() {
return (
<div style={{ display: 'grid', gap: '1rem' }}>
<Legend
items={labels.map((label, i) => ({
label,
level: heatmapLevel(samples[i], breaks) || undefined,
}))}
/>
<Heatmap
title={meta.title}
description="Login tickets peak on Monday at 41; billing tickets peak on Friday at 31."
data={data}
row="category"
column="day"
value="count"
columns={days}
breaks={breaks}
binLabels={labels}
legend={false}
/>
<BarChart
title="Support tickets per day"
description="Thursday is the busiest day with 66 tickets; Wednesday is the quietest with 51."
data={perDay}
x="day"
y="count"
height={180}
/>
</div>
)
}
Parameters of heatmapLevel #
| Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
value | unknown | — | Yes | — |
breaks | readonly number[] | — | Yes | — |
Returns SeqLevel | 0