
100% normalized stacked area chart visualizing sector percentage share.
components/tanstack-charts/area/normalized-stacked-area.tsx
import { type ChartPoint, areaY, defineChart, ruleY, stack } 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 { PieChart } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface ShareDatum {
date: Date;
industry: string;
unemployed: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): ShareDatum[] {
const baseDate = new Date(2025, 0, 1);
const results: ShareDatum[] = [];
for (let i = 0; i < 10; i++) {
const d = new Date(baseDate);
d.setMonth(baseDate.getMonth() + i);
results.push({ date: d, industry: "Tech", unemployed: 150 + Math.sin(i * 0.5) * 30 });
results.push({ date: d, industry: "Finance", unemployed: 220 + Math.cos(i * 0.5) * 40 });
results.push({ date: d, industry: "Services", unemployed: 180 + Math.sin(i * 0.8) * 20 });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const dateVal = (points[0].datum as ShareDatum)?.date;
const dateObj = dateVal ? (dateVal instanceof Date ? dateVal : new Date(dateVal)) : null;
const titleStr =
dateObj && !isNaN(dateObj.getTime())
? dateObj.toLocaleDateString("en-US", { month: "short", year: "numeric" })
: "";
return {
title: titleStr,
rows: points.map((p) => {
const d = p.datum as ShareDatum;
return {
label: d.industry,
value: `${d.unemployed.toFixed(0)}k volume`,
color: p.color || "var(--chart-1)",
};
}),
};
}
export function NormalizedStackedArea() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
areaY(data, {
id: "normalized-area",
x: "date",
y: "unemployed",
color: "industry",
fillOpacity: 0.8,
layout: stack({ offset: "normalize" }),
}),
ruleY([0], { stroke: "var(--border)" }),
],
scales: {
x: {
scale: scaleUtc,
axis: {
line: false,
label: "Month",
ticks: {
size: 0,
padding: 10,
format: (d: any) => {
const dateObj = d instanceof Date ? d : new Date(d);
return isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short" });
},
},
},
},
y: {
scale: scaleLinear().domain([0, 1]),
grid: true,
axis: {
line: false,
label: "Relative Share (%)",
ticks: {
size: 0,
format: (v: number) => `${(v * 100).toFixed(0)}%`,
},
},
},
},
color: {
domain: ["Tech", "Finance", "Services"],
range: ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)"],
},
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>Normalized Sector Share</CardTitle>
<CardDescription>
100% normalized stacked area chart displaying proportional market share
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Normalized Sector Share Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Proportions total 100% across all observed temporal windows{" "}
<PieChart className="h-4 w-4 text-violet-500" />
</div>
<div className="text-muted-foreground leading-none">
Normalized offset scales each slice to represent percentage share of sum
</div>
</CardFooter>
</Card>
);
}
export default NormalizedStackedArea;