{"spec_id":"histogram-stacked","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-stacked: Stacked Histogram\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 86/100 | Updated: 2026-11-08\nimport { BarChart } from \"@mui/x-charts/BarChart\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TARGET_BINS = 15; // about this many bins; the width is rounded to a 1-2-2.5-5 step\nconst NICE_STEPS = [1, 2, 2.5, 5, 10];\n\n// Columns: set these to your data's column names\nconst DISTANCE = \"Commute Distance (km)\"; // role: values\nconst MODE = \"Transport mode\"; // role: group\n\n// Data: replace this block with your own records, one object per observation\n// One-way commute distance of 640 employees by their primary transport mode.\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (state * 1664525 + 1013904223) % 4294967296;\n    return state / 4294967296;\n  };\n  const modes = [\n    { name: \"Car\", mean: 19, sd: 6.5, n: 260 },\n    { name: \"Public transit\", mean: 13, sd: 5, n: 220 },\n    { name: \"Bike\", mean: 6, sd: 2.5, n: 160 },\n  ];\n  return modes.flatMap((mode) =>\n    Array.from({ length: mode.n }, () => {\n      const z = Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n      return { [MODE]: mode.name, [DISTANCE]: Number(Math.min(Math.max(mode.mean + z * mode.sd, 0), 35.99).toFixed(2)) };\n    }),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[DISTANCE] != null);\nconst groups = [...new Set(rows.map((d) => d[MODE]))];\nconst values = rows.map((d) => d[DISTANCE]);\nconst minValue = Math.min(...values);\nconst maxValue = Math.max(...values);\nconst rawWidth = (maxValue - minValue) / TARGET_BINS;\nconst magnitude = 10 ** Math.floor(Math.log10(rawWidth));\nconst binWidth = NICE_STEPS.map((s) => s * magnitude).find((w) => w >= rawWidth);\nconst binStart = Math.floor(minValue / binWidth) * binWidth;\nconst binCount = Math.max(1, Math.ceil((maxValue - binStart) / binWidth));\n// Bin edges shared by every group; bins [edge, edge + width), the last one closed\nconst edges = Array.from({ length: binCount + 1 }, (_, i) => Number((binStart + i * binWidth).toPrecision(12)));\nconst binLabels = edges.slice(0, -1).map((lo, i) => `${lo}–${edges[i + 1]}`);\n\nconst groupStats = groups.map((group) => {\n  const groupValues = rows.filter((d) => d[MODE] === group).map((d) => d[DISTANCE]);\n  const counts = new Array(binCount).fill(0);\n  for (const v of groupValues) counts[Math.min(binCount - 1, Math.floor((v - binStart) / binWidth))] += 1;\n  return { group, counts, n: groupValues.length };\n});\n\nconst unit = DISTANCE.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst TITLE = \"histogram-stacked · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${MODE}: ${groupStats.map((g) => `${g.group} n = ${g.n}`).join(\" · \")} · bin width ${binWidth}${unit ? ` ${unit}` : \"\"}`;\nconst COUNT_LABEL = \"Frequency (count per bin)\";\nconst HEADER_H = 76;\nconst LEGEND_H = 44;\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\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.5 }}>{SUBTITLE}</Typography>\n      </Box>\n      <BarChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        borderRadius={0}\n        grid={{ horizontal: true }}\n        margin={{ top: 12, right: 40, bottom: 8, left: 24 }}\n        // Stacked in the data's group order, the same in every bin\n        series={groupStats.map((g, i) => ({\n          id: `group-${i}`,\n          data: g.counts,\n          label: g.group,\n          color: t.palette[i],\n          stack: \"total\",\n          highlightScope: { highlight: \"series\", fade: \"global\" },\n        }))}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: binLabels,\n            // Contiguous bins: the segment stroke marks bin and group edges\n            categoryGapRatio: 0,\n            height: 64,\n            label: DISTANCE,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            width: 72,\n            label: COUNT_LABEL,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink, gap: \"28px\" },\n          },\n        }}\n        sx={{\n          \"& .MuiBarChart-element\": { stroke: t.pageBg, strokeWidth: 1.5 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      />\n    </Box>\n  );\n}\n"}