components/tanstack-charts/area/quantile-ribbon.tsx
import { type ChartPoint, areaY, defineChart, groupBy, lineY, quantile } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { Spline } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface IndustryDatum {
industry: string;
date: Date;
unemployed: number;
}
interface QuantileRow {
date: Date;
lower: number;
median: number;
upper: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): IndustryDatum[] {
const results: IndustryDatum[] = [];
const industries = ["Trade", "Manufacturing", "Tech", "Services", "Health", "Construction"];
const dates: Date[] = [];
for (let m = 0; m < 24; m++) {
dates.push(new Date(Date.UTC(2023, m, 1)));
}
dates.forEach((d) => {
industries.forEach((ind, idx) => {
const base = 80 + Math.sin(d.getTime() * 0.000000001 + idx) * 30 + (idx + 1) * 20;
results.push({
industry: ind,
date: d,
unemployed: Math.max(20, Math.round(base + (Math.random() - 0.5) * 25)),
});
});
});
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as QuantileRow;
if (!d || !d.date) return { title: "", rows: [] };
const dateObj = d.date instanceof Date ? d.date : new Date(d.date);
const dateStr = isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", year: "numeric", timeZone: "UTC" });
return {
title: dateStr,
rows: [
{ label: "90th Percentile (Upper)", value: `${d.upper}k`, color: "var(--chart-1)" },
{ label: "50th Percentile (Median)", value: `${d.median}k`, color: "var(--foreground)" },
{ label: "10th Percentile (Lower)", value: `${d.lower}k`, color: "var(--chart-2)" },
],
};
}
export function QuantileRibbon() {
const rawData = useMemo(() => generateDemoData(), []);
const quantileRows = useMemo(() => {
return groupBy(rawData, {
by: "date",
outputs: {
lower: { value: "unemployed", reduce: quantile(0.1) },
median: { value: "unemployed", reduce: quantile(0.5) },
upper: { value: "unemployed", reduce: quantile(0.9) },
},
}) as unknown as QuantileRow[];
}, [rawData]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
areaY(quantileRows, {
id: "quantile-ribbon",
x: "date",
y1: "lower",
y2: "upper",
key: (row: QuantileRow) =>
row?.date
? row.date instanceof Date
? row.date.getTime()
: new Date(row.date).getTime()
: 0,
fill: "var(--chart-1)",
fillOpacity: 0.25,
}),
lineY(quantileRows, {
id: "median-line",
x: "date",
y: "median",
key: (row: QuantileRow) =>
row?.date
? row.date instanceof Date
? row.date.getTime()
: new Date(row.date).getTime()
: 0,
stroke: "var(--chart-1)",
strokeWidth: 2.25,
}),
],
scales: {
x: {
scale: scaleUtc,
axis: { label: "Timeline Month" },
},
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Unemployment Range (Thousands)" },
},
},
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
keyboard: true,
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "pointer",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[quantileRows],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>10th–90th Quantile Distribution Ribbon</CardTitle>
<CardDescription>
Percentile band area chart tracking median line within 10th-90th quantile bounds
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="10th–90th Quantile Distribution Ribbon Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Ribbon encapsulates 80% central spread across industry metrics{" "}
<Spline className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Quantile reducer computes robust non-parametric confidence bands
</div>
</CardFooter>
</Card>
);
}
export default QuantileRibbon;