
A stacked bar chart comparing desktop and mobile visitors with legend built with TanStack Charts.
components/tanstack-charts/bar/bar-chart-stacked.tsx
import { type ChartPoint, barY, defineChart, 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 { scaleBand, scaleLinear } from "d3-scale";
import { TrendingUp } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface SeriesDatum {
month: string;
series: "desktop" | "mobile";
value: number;
}
function generateDemoData(): SeriesDatum[] {
return [
{ month: "January", series: "desktop", value: 186 },
{ month: "January", series: "mobile", value: 80 },
{ month: "February", series: "desktop", value: 305 },
{ month: "February", series: "mobile", value: 200 },
{ month: "March", series: "desktop", value: 237 },
{ month: "March", series: "mobile", value: 120 },
{ month: "April", series: "desktop", value: 73 },
{ month: "April", series: "mobile", value: 190 },
{ month: "May", series: "desktop", value: 209 },
{ month: "May", series: "mobile", value: 130 },
{ month: "June", series: "desktop", value: 214 },
{ month: "June", series: "mobile", value: 140 },
];
}
const twoSeries = ["desktop", "mobile"] as const;
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function titleCase(value: string) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
return {
title: String(points[0]?.xValue ?? ""),
rows: points.map((point) => ({
label: titleCase(
String(point.group ?? point.markId.replace(/-?(bars|lines|areas|slices|values|radar)$/u, "")),
),
value: Number(point.yValue ?? point.xValue ?? 0).toLocaleString("en-US"),
color: point.color,
})),
};
}
export function BarChartStacked() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
motion: {
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
},
marks: [
barY(data, {
id: "visitor-bars",
x: "month",
y: "value",
z: "series",
color: "series",
key: (row: SeriesDatum) => `${row.month}:${row.series}`,
layout: stack({ order: twoSeries }),
radius: 4,
}),
],
scales: {
x: {
scale: () => scaleBand<string>().paddingInner(0.2).paddingOuter(0.1),
axis: {
line: false,
ticks: {
size: 0,
padding: 10,
format: (value: string) => value.slice(0, 3),
},
},
},
y: { scale: scaleLinear, grid: true, axis: false },
},
color: { domain: twoSeries, range: ["var(--chart-1)", "var(--chart-2)"] },
margin: { top: 5, right: 5, bottom: 35, left: 5 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
focus: "group-x",
tooltip: {
use: tooltip,
motion: { type: "spring", stiffness: 170, damping: 18 },
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
sort: "color-domain",
content: (points) => shadcnTooltipContent(points),
},
},
),
[data],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Tiered Subscription Breakdown</CardTitle>
<CardDescription>Monthly growth split between Pro and Enterprise tiers</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Tiered Subscription Breakdown Chart"
/>
</div>
<div className="flex items-center justify-center gap-4 text-xs">
<div className="flex items-center gap-1.5">
<span className="h-2.5 w-2.5 rounded-full bg-[var(--chart-1)]" />
<span className="text-muted-foreground">Desktop</span>
</div>
<div className="flex items-center gap-1.5">
<span className="h-2.5 w-2.5 rounded-full bg-[var(--chart-2)]" />
<span className="text-muted-foreground">Mobile</span>
</div>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Enterprise tier expansion up by 5.2% this month <TrendingUp className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">Showing total visitors for the last 6 months</div>
</CardFooter>
</Card>
);
}
export default BarChartStacked;