components/tanstack-charts/area/hexbin-density.tsx
import { type ChartPoint, defineChart } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { hexbin } from "@tanstack/charts/spatial/hexbin";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear, scaleThreshold } from "d3-scale";
import { Hexagon } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface HexDatum {
weight: number;
mpg: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): HexDatum[] {
const results: HexDatum[] = [];
for (let i = 0; i < 250; i++) {
const weight = 1800 + Math.random() * 3200;
const baseMpg = 45 - (weight - 1800) * 0.008;
const mpg = Math.max(8, baseMpg + (Math.random() - 0.5) * 12);
results.push({ weight, mpg });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const datum = points[0].datum as { x: number; y: number; count: number };
if (!datum) return { title: "", rows: [] };
return {
title: `Bin Center: ${datum.x?.toFixed(0)} lb, ${datum.y?.toFixed(1)} mpg`,
rows: [{ label: "Data Point Count", value: `${datum.count} items`, color: "var(--chart-1)" }],
};
}
export function HexbinDensity() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
hexbin(data, {
x: "weight",
y: "mpg",
binWidth: 24,
color: "count",
r: 11,
stroke: "var(--background)",
strokeWidth: 0.75,
}),
],
scales: {
x: {
scale: scaleLinear().domain([1500, 5200]),
grid: true,
axis: { label: "Vehicle Weight (lb)" },
},
y: {
scale: scaleLinear().domain([5, 50]),
grid: true,
axis: { label: "Fuel Economy (mpg)" },
},
},
color: {
scale: scaleThreshold<number, string>,
domain: [3, 8, 15],
range: ["var(--chart-5)", "var(--chart-3)", "var(--chart-2)", "var(--chart-1)"],
},
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],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Hexagonal Point Density Binned Plot</CardTitle>
<CardDescription>
Spatial hexbin clustering mapping vehicle weight vs fuel efficiency density
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Hexagonal Point Density Binned Plot Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
High density concentration around 2,500 lbs & 30 mpg{" "}
<Hexagon className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Hexagonal tessellation avoids visual scatter plot overlap in dense bivariate distributions
</div>
</CardFooter>
</Card>
);
}
export default HexbinDensity;