{"spec_id":"bar-stacked","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-stacked: Stacked Bar Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { BarChart } from \"@mui/x-charts/BarChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"Cloud Costs by Service · bar-stacked · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 44;\nconst PAD_SHARE = 0.1; // headroom above the tallest stack for its total label\n\n// Columns: set these to your data's column names\nconst MONTH = \"Month\"; // role: category\nconst SERVICE = \"Service\"; // role: component\nconst SPEND = \"Spend (thousand USD)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Monthly cloud infrastructure spend by service, first half of the year\nconst data = [\n  { [MONTH]: \"Jan\", [SERVICE]: \"Compute\", [SPEND]: 38 },\n  { [MONTH]: \"Feb\", [SERVICE]: \"Compute\", [SPEND]: 41 },\n  { [MONTH]: \"Mar\", [SERVICE]: \"Compute\", [SPEND]: 44 },\n  { [MONTH]: \"Apr\", [SERVICE]: \"Compute\", [SPEND]: 47 },\n  { [MONTH]: \"May\", [SERVICE]: \"Compute\", [SPEND]: 52 },\n  { [MONTH]: \"Jun\", [SERVICE]: \"Compute\", [SPEND]: 58 },\n  { [MONTH]: \"Jan\", [SERVICE]: \"Database\", [SPEND]: 21 },\n  { [MONTH]: \"Feb\", [SERVICE]: \"Database\", [SPEND]: 22 },\n  { [MONTH]: \"Mar\", [SERVICE]: \"Database\", [SPEND]: 24 },\n  { [MONTH]: \"Apr\", [SERVICE]: \"Database\", [SPEND]: 25 },\n  { [MONTH]: \"May\", [SERVICE]: \"Database\", [SPEND]: 27 },\n  { [MONTH]: \"Jun\", [SERVICE]: \"Database\", [SPEND]: 29 },\n  { [MONTH]: \"Jan\", [SERVICE]: \"Storage\", [SPEND]: 14 },\n  { [MONTH]: \"Feb\", [SERVICE]: \"Storage\", [SPEND]: 15 },\n  { [MONTH]: \"Mar\", [SERVICE]: \"Storage\", [SPEND]: 16 },\n  { [MONTH]: \"Apr\", [SERVICE]: \"Storage\", [SPEND]: 17 },\n  { [MONTH]: \"May\", [SERVICE]: \"Storage\", [SPEND]: 18 },\n  { [MONTH]: \"Jun\", [SERVICE]: \"Storage\", [SPEND]: 20 },\n  { [MONTH]: \"Jan\", [SERVICE]: \"Networking\", [SPEND]: 9 },\n  { [MONTH]: \"Feb\", [SERVICE]: \"Networking\", [SPEND]: 10 },\n  { [MONTH]: \"Mar\", [SERVICE]: \"Networking\", [SPEND]: 10 },\n  { [MONTH]: \"Apr\", [SERVICE]: \"Networking\", [SPEND]: 11 },\n  { [MONTH]: \"May\", [SERVICE]: \"Networking\", [SPEND]: 12 },\n  { [MONTH]: \"Jun\", [SERVICE]: \"Networking\", [SPEND]: 13 },\n];\n\n// Plot: reads only data and the constants above\n// Months keep their order of appearance; each service keeps its colour by first appearance\nconst months = [...new Set(data.map((d) => d[MONTH]))];\nconst services = [...new Set(data.map((d) => d[SERVICE]))];\nconst values = services.map((s) =>\n  months.map((m) => data.find((d) => d[MONTH] === m && d[SERVICE] === s)?.[SPEND] ?? null),\n);\nconst serviceTotals = values.map((vs) => vs.reduce((a, v) => a + (v ?? 0), 0));\n// Same stack order in every bar: the largest service overall at the bottom\nconst stackOrder = services.map((_, i) => i).sort((a, b) => serviceTotals[b] - serviceTotals[a]);\n\nconst totals = months.map((_, mi) => values.reduce((a, vs) => a + (vs[mi] ?? 0), 0));\nconst maxTotal = Math.max(...totals);\n\nconst growth = values.map((vs) => {\n  const known = vs.filter((v) => v != null);\n  return known.length > 1 && known[0] ? known[known.length - 1] / known[0] - 1 : -Infinity;\n});\nconst fastest = growth.indexOf(Math.max(...growth));\nconst pct = (r: number) => `${r >= 0 ? \"+\" : \"\"}${Math.round(r * 100)}%`;\nconst SUBTITLE = [\n  `${services.length} services across ${months.length} months, largest at the bottom`,\n  totals[0] ? `stack total ${totals[0]} → ${totals[totals.length - 1]} (${pct(totals[totals.length - 1] / totals[0] - 1)})` : null,\n  Number.isFinite(growth[fastest]) ? `fastest growth: ${services[fastest]} (${pct(growth[fastest])})` : null,\n]\n  .filter(Boolean)\n  .join(\" · \");\n\n// Custom layer: each stack's total, just above the top of the stack\nfunction TotalLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {months.map((m, i) => (\n        <text\n          key={m}\n          x={xScale(m) + xScale.bandwidth() / 2}\n          y={yScale(totals[i]) - 10}\n          textAnchor=\"middle\"\n          fontSize={16}\n          fontWeight={600}\n          fill={t.ink}\n        >\n          {totals[i].toLocaleString(\"en-US\")}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, px: \"40px\", pt: \"18px\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ color: t.ink, fontSize: \"22px\", fontWeight: 600, lineHeight: 1.2 }}>\n          {TITLE}\n        </Typography>\n        <Typography sx={{ color: t.inkSoft, fontSize: \"15px\", lineHeight: 1.2, mt: \"8px\" }}>\n          {SUBTITLE}\n        </Typography>\n      </Box>\n      <BarChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        borderRadius={3}\n        grid={{ horizontal: true }}\n        series={stackOrder.map((i) => ({\n          id: `s${i}`,\n          label: services[i],\n          stack: \"total\",\n          color: t.palette[i],\n          data: values[i],\n        }))}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: months,\n            label: MONTH,\n            height: 64,\n            categoryGapRatio: 0.4,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 16, fill: t.ink },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: maxTotal * (1 + PAD_SHARE),\n            label: SPEND,\n            width: 84,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        margin={{ top: 16, right: 40, bottom: 8, left: 24 }}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          \"& .MuiBarChart-element\": { stroke: t.elevatedBg, strokeWidth: 1 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <TotalLabels />\n      </BarChart>\n    </Box>\n  );\n}\n"}