components/tanstack-charts/bar/cumulative-histogram.tsx
import { type ChartPoint, binX, cumulative, defineChart, rect } 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 { thresholdScott } from "d3-array";
import { scaleLinear } from "d3-scale";
import { BarChart2 } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface WeightDatum {
weight: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): WeightDatum[] {
const results: WeightDatum[] = [];
for (let i = 0; i < 80; i++) {
// Normal distribution approximation
const weight = 65 + (Math.sin(i) + Math.cos(i * 1.5) + Math.sin(i * 0.7)) * 12;
results.push({ weight });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const p = points[0];
const d = p.datum as any;
if (!d) return { title: "", rows: [] };
return {
title: `Weight Range: ${d.x1.toFixed(1)} – ${d.x2.toFixed(1)} kg`,
rows: [
{
label: "Cumulative Total",
value: `${d.cumulativeCount} subjects`,
color: "var(--chart-1)",
},
],
};
}
export function CumulativeHistogram() {
const data = useMemo(() => generateDemoData(), []);
const cumulativeBins = useMemo(() => {
const bins = binX(data, {
value: "weight",
thresholds: thresholdScott,
outputs: { count: { reduce: "count" } },
});
return cumulative(bins, {
orderBy: "x1",
outputs: { cumulativeCount: { value: "count", reduce: "sum" } },
});
}, [data]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
rect(cumulativeBins, {
id: "cumulative-rects",
x1: "x1",
x2: "x2",
y1: () => 0,
y2: "cumulativeCount",
fill: "var(--chart-1)",
inset: 1,
}),
],
scales: {
x: {
scale: scaleLinear,
grid: true,
axis: {
line: false,
label: "Weight (kg)",
ticks: { size: 0 },
},
},
y: {
scale: scaleLinear,
grid: true,
axis: {
line: false,
label: "Cumulative Count",
ticks: { size: 0 },
},
},
},
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
focus: "group-x",
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[cumulativeBins],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Cumulative Population Distribution</CardTitle>
<CardDescription>Binned cumulative frequency histogram of subject body weights</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Cumulative Population Distribution Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
80% of cohort falls below 78kg weight threshold <BarChart2 className="h-4 w-4 text-cyan-500" />
</div>
<div className="text-muted-foreground leading-none">
Bar height reflects total cumulative count up to each bin upper bound
</div>
</CardFooter>
</Card>
);
}
export default CumulativeHistogram;