components/tanstack-charts/bar/marimekko-mosaic.tsx
import { type ChartPoint, defineChart, groupBy, mosaicY, rect, select, 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 { PieChart } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface SurveyRow {
Question: string;
Response: string;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const questions = ["Usability", "Performance", "Value", "Support"];
const responses = ["Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree"];
function generateDemoData(): SurveyRow[] {
const results: SurveyRow[] = [];
questions.forEach((q, qIdx) => {
const count = 50 + qIdx * 25;
for (let i = 0; i < count; i++) {
const rIdx = Math.min(4, Math.floor(Math.random() * 3 + qIdx * 0.5));
results.push({ Question: q, Response: responses[rIdx] });
}
});
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as { xValue: string; yValue: string; proportion?: number };
if (!d) return { title: "", rows: [] };
return {
title: `${d.xValue}: ${d.yValue}`,
rows: [{ label: "Segment", value: `${d.yValue}`, color: "var(--chart-1)" }],
};
}
export function MarimekkoMosaic() {
const data = useMemo(() => generateDemoData(), []);
const counts = useMemo(() => {
return groupBy(data, {
by: {
Question: "Question",
Response: "Response",
},
outputs: { count: { reduce: "count" } },
});
}, [data]);
const cells = useMemo(() => {
return mosaicY(counts, {
x: "Question",
y: "Response",
value: "count",
yOrder: responses,
});
}, [counts]);
const labels = useMemo(() => {
return select(cells, {
by: "xValue",
select: "first",
});
}, [cells]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
rect(cells, {
id: "response-cells",
x: "x",
x1: "x1",
x2: "x2",
y: "y",
y1: "y1",
y2: "y2",
color: "yValue",
key: (datum: { xValue: string; yValue: string }) => `${datum.xValue}:${datum.yValue}`,
inset: 1,
}),
text(labels, {
id: "question-labels",
x: "x",
y: () => 1.05,
text: "Question",
key: "xValue",
fill: "var(--foreground)",
fontSize: 10,
fontWeight: 600,
}),
],
scales: {
x: {
scale: scaleLinear().domain([0, 1]),
axis: {
ticks: { format: (v: number) => `${Math.round(v * 100)}%` },
label: "Question Share of Total",
},
},
y: {
scale: scaleLinear().domain([0, 1.12]),
axis: {
ticks: { format: (v: number) => `${Math.round(v * 100)}%` },
label: "Within-Question Share",
},
},
},
color: {
domain: responses,
range: [
"var(--chart-5)",
"var(--chart-4)",
"var(--chart-3)",
"var(--chart-2)",
"var(--chart-1)",
],
},
margin: { top: 28, 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),
},
},
),
[cells, labels],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Marimekko Survey Mosaic Chart</CardTitle>
<CardDescription>
Variable-width mosaic chart where column width and height encode 2D survey proportions
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Marimekko Survey Mosaic Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Support question represents largest total response volume{" "}
<PieChart className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Mosaic area maps total counts as column width × row height product
</div>
</CardFooter>
</Card>
);
}
export default MarimekkoMosaic;