components/tanstack-charts/line/connected-scatter.tsx
import { type ChartPoint, arrow, d3Curve, defineChart, dot, lineY, rollingWindow, text } 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 } from "d3-scale";
import { curveCatmullRom } from "d3-shape";
import { Route } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface DrivingDatum {
year: number;
miles: number;
gas: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): DrivingDatum[] {
const results: DrivingDatum[] = [];
let miles = 4000;
let gas = 1.2;
for (let yr = 1980; yr <= 2024; yr += 2) {
miles += (Math.sin(yr * 0.2) + 1.5) * 200;
gas += (Math.cos(yr * 0.3) + 0.2) * 0.15;
results.push({
year: yr,
miles: Math.round(miles),
gas: Number(gas.toFixed(2)),
});
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as DrivingDatum;
if (!d) return { title: "", rows: [] };
return {
title: `Year ${d.year}`,
rows: [
{ label: "Miles Driven / Person", value: `${d.miles.toLocaleString()} mi`, color: "var(--chart-1)" },
{ label: "Gasoline Price", value: `$${d.gas.toFixed(2)}/gal`, color: "var(--foreground)" },
],
};
}
export function ConnectedScatter() {
const data = useMemo(() => generateDemoData(), []);
const directionPairs = useMemo(() => {
return rollingWindow(data, {
orderBy: "year",
size: 2,
partial: false,
outputs: {},
}).filter(({ sourceIndexes }) => (sourceIndexes[1] ?? -1) % 4 === 0);
}, [data]);
const labels = useMemo(() => data.filter((d) => d.year % 10 === 0), [data]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(data, {
id: "driving-path",
x: "miles",
y: "gas",
stroke: "var(--chart-1)",
strokeWidth: 2.25,
curve: d3Curve(curveCatmullRom.alpha(0.5)),
}),
dot(data, {
id: "driving-points",
x: "miles",
y: "gas",
fill: "var(--chart-2)",
r: 3.5,
}),
arrow(directionPairs, {
id: "direction-arrows",
x1: ({ source }) => source[0]?.miles,
y1: ({ source }) => source[0]?.gas,
x2: "miles",
y2: "gas",
stroke: "var(--chart-2)",
strokeWidth: 1.5,
headLength: 6,
}),
text(labels, {
id: "year-labels",
x: "miles",
y: "gas",
text: (row: DrivingDatum) => `${row.year}`,
fill: "var(--foreground)",
anchor: "middle",
dy: -10,
fontSize: 10,
fontWeight: 600,
}),
],
scales: {
x: {
scale: scaleLinear,
grid: true,
axis: { label: "Miles Driven per Person" },
},
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Cost of Gasoline ($/gal)" },
},
},
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),
},
},
),
[data, directionPairs, labels],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Directed Connected Scatterplot</CardTitle>
<CardDescription>
2D path trajectory tracking driving distance vs gas prices across time
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Directed Connected Scatterplot Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Trajectory arrows illustrate chronological progression over 40 years{" "}
<Route className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Connected scatterplot connects 2D points sequentially to visualize non-monotonic relationship
dynamics
</div>
</CardFooter>
</Card>
);
}
export default ConnectedScatter;