{"spec_id":"bar-stacked-labeled","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-stacked-labeled: Stacked Bar Chart with Total Labels\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/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 = \"Project Budget by Phase · bar-stacked-labeled · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 44;\nconst PAD_SHARE = 0.12; // headroom above the tallest stack for its total label\nconst MIN_LABEL_PX = 30; // a segment shorter than this keeps no segment label\n// Fixed label inks: segment fills keep their hex in both themes, so the ink follows the fill\nconst DARK_INK = \"#1A1A17\";\nconst LIGHT_INK = \"#FAF8F1\";\n\n// Columns: set these to your data's column names\nconst PHASE = \"Project phase\"; // role: category\nconst COST_TYPE = \"Cost type\"; // role: component\nconst COST = \"Cost (thousand USD)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Software project budget, three cost types per delivery phase\nconst data = [\n  { [PHASE]: \"Planning\", [COST_TYPE]: \"Labor\", [COST]: 18 },\n  { [PHASE]: \"Design\", [COST_TYPE]: \"Labor\", [COST]: 32 },\n  { [PHASE]: \"Development\", [COST_TYPE]: \"Labor\", [COST]: 58 },\n  { [PHASE]: \"Testing\", [COST_TYPE]: \"Labor\", [COST]: 34 },\n  { [PHASE]: \"Deployment\", [COST_TYPE]: \"Labor\", [COST]: 22 },\n  { [PHASE]: \"Planning\", [COST_TYPE]: \"Materials\", [COST]: 6 },\n  { [PHASE]: \"Design\", [COST_TYPE]: \"Materials\", [COST]: 14 },\n  { [PHASE]: \"Development\", [COST_TYPE]: \"Materials\", [COST]: 20 },\n  { [PHASE]: \"Testing\", [COST_TYPE]: \"Materials\", [COST]: 10 },\n  { [PHASE]: \"Deployment\", [COST_TYPE]: \"Materials\", [COST]: 8 },\n  { [PHASE]: \"Planning\", [COST_TYPE]: \"Equipment\", [COST]: 4 },\n  { [PHASE]: \"Design\", [COST_TYPE]: \"Equipment\", [COST]: 10 },\n  { [PHASE]: \"Development\", [COST_TYPE]: \"Equipment\", [COST]: 16 },\n  { [PHASE]: \"Testing\", [COST_TYPE]: \"Equipment\", [COST]: 6 },\n  { [PHASE]: \"Deployment\", [COST_TYPE]: \"Equipment\", [COST]: 12 },\n];\n\n// Plot: reads only data and the constants above\n// Phases keep their delivery order; cost types stack bottom to top in order of first appearance\nconst phases = [...new Set(data.map((d) => d[PHASE]))];\nconst costTypes = [...new Set(data.map((d) => d[COST_TYPE]))];\nconst values = costTypes.map((c) =>\n  phases.map((p) => data.find((d) => d[PHASE] === p && d[COST_TYPE] === c)?.[COST] ?? null),\n);\nconst totals = phases.map((_, pi) => values.reduce((a, vs) => a + (vs[pi] ?? 0), 0));\nconst maxTotal = Math.max(...totals);\nconst grandTotal = totals.reduce((a, v) => a + v, 0);\nconst largest = totals.indexOf(maxTotal);\n\n// Segment label ink per cost type: whichever fixed ink contrasts more with the fill\nconst labelInks = costTypes.map((_, i) => {\n  const [R, G, B] = [1, 3, 5].map((k) => {\n    const c = parseInt(t.palette[i].slice(k, k + 2), 16) / 255;\n    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n  });\n  const lum = 0.2126 * R + 0.7152 * G + 0.0722 * B;\n  return (lum + 0.05) / 0.0603 >= 0.985 / (lum + 0.05) ? DARK_INK : LIGHT_INK;\n});\n\nconst SUBTITLE = `${phases.length} phases, ${costTypes.length} cost types · budget total ${grandTotal.toLocaleString(\"en-US\")} · largest phase: ${phases[largest]} (${Math.round((maxTotal / grandTotal) * 100)}% of the total)`;\n\n// Custom layer: each stack's total, directly above the top of the stack\nfunction TotalLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {phases.map((p, i) => (\n        <text\n          key={p}\n          x={xScale(p) + xScale.bandwidth() / 2}\n          y={yScale(totals[i]) - 12}\n          textAnchor=\"middle\"\n          fontSize={20}\n          fontWeight={700}\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        colors={t.palette}\n        skipAnimation\n        borderRadius={4}\n        grid={{ horizontal: true }}\n        series={costTypes.map((c, i) => ({\n          id: `c${i}`,\n          label: c,\n          stack: \"total\",\n          data: values[i],\n          barLabel: (item: { value: number | null }, ctx: { bar: { height: number } }) =>\n            item.value == null || ctx.bar.height < MIN_LABEL_PX ? null : item.value.toLocaleString(\"en-US\"),\n        }))}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: phases,\n            label: PHASE,\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: COST,\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: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          \"& .MuiBarChart-element\": { stroke: t.elevatedBg, strokeWidth: 1.5 },\n          \"& .MuiBarChart-label\": { fontSize: 15, fontWeight: 500 },\n          ...Object.fromEntries(costTypes.map((_, i) => [`& [data-series=\"c${i}\"] .MuiBarChart-label`, { fill: labelInks[i] }])),\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"}