components/tanstack-charts/bar/boxplot.tsx
import { type ChartPoint, boxY, defineChart } 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 { scaleBand, scaleLinear } from "d3-scale";
import { BarChart3 } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface BoxplotDatum {
Expt: number;
Speed: number;
Run: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): BoxplotDatum[] {
const results: BoxplotDatum[] = [];
const baseSpeeds = [850, 920, 880, 810, 890];
for (let expt = 1; expt <= 5; expt++) {
const base = baseSpeeds[expt - 1];
for (let run = 1; run <= 12; run++) {
const spread = Math.sin(run * 1.3 + expt) * 60 + Math.cos(run * 0.7) * 30;
results.push({ Expt: expt, Speed: Math.round(base + spread), Run: run });
}
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const datum = points[0].datum as any;
if (!datum) return { title: "", rows: [] };
if (datum.kind === "summary") {
return {
title: `Experiment ${datum.category}`,
rows: [
{ label: "Median", value: `${datum.median.toFixed(1)} km/s`, color: "var(--chart-1)" },
{
label: "IQR (Q1 - Q3)",
value: `${datum.q1.toFixed(1)} – ${datum.q3.toFixed(1)}`,
color: "var(--foreground)",
},
],
};
}
return {
title: `Experiment ${datum.category} Outlier`,
rows: [{ label: "Speed", value: `${datum.value.toFixed(1)} km/s`, color: "var(--chart-2)" }],
};
}
export function BoxplotChart() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
boxY(data, {
id: "experiment-boxplot",
x: "Expt",
y: "Speed",
key: (row: BoxplotDatum) => `${row.Expt}:${row.Run}`,
fill: "var(--chart-1)",
stroke: "var(--chart-1)",
inset: 12,
r: 3,
}),
],
scales: {
x: {
scale: () => scaleBand<number>().padding(0.25),
axis: {
line: false,
label: "Experiment Trial",
ticks: { size: 0, padding: 10 },
},
},
y: {
scale: scaleLinear().domain([700, 1050]),
grid: true,
axis: {
line: false,
label: "Speed Variance",
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),
},
},
),
[data],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Experiment Speed Distribution</CardTitle>
<CardDescription>Grouped quartile boxplots highlighting median and outlier spreads</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Experiment Speed 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">
Trial 2 demonstrated tightest interquartile stability{" "}
<BarChart3 className="h-4 w-4 text-indigo-500" />
</div>
<div className="text-muted-foreground leading-none">
Boxes enclose the middle 50% of readings; whiskers extend to non-outlier limits
</div>
</CardFooter>
</Card>
);
}
export default BoxplotChart;