{"spec_id":"histogram-overlapping","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-overlapping: Overlapping Histograms\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 { useDrawingArea, useXScale } 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 TARGET_BINS = 13; // 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];\nconst FILL_ALPHA_HEX = \"8C\"; // 55 % opacity, baked into the colour so the legend swatches match\nconst Y_HEADROOM_SHARE = 0.18; // room above the tallest bar for the mean labels\n\n// Columns: set these to your data's column names\nconst SCORE = \"Exam Score (0–100)\"; // role: values\nconst GROUP = \"Group\"; // role: group\n\n// Data: replace this block with your own records, one object per observation\n// Exam scores of 240 students per arm of an A/B test of a new tutoring method.\nconst data = (() => {\n  let state = 42 >>> 0;\n  const rand = () => {\n    state = (state * 1664525 + 1013904223) >>> 0;\n    return state / 4294967296;\n  };\n  const gaussian = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const arms = [\n    { name: \"Control group\", mean: 68, sd: 11 },\n    { name: \"Treatment group\", mean: 76, sd: 9 },\n  ];\n  return arms.flatMap((arm) =>\n    Array.from({ length: 240 }, () => ({\n      [GROUP]: arm.name,\n      [SCORE]: Number(Math.min(100, Math.max(0, arm.mean + arm.sd * gaussian())).toFixed(1)),\n    })),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[SCORE] != null);\nconst groups = [...new Set(rows.map((d) => d[GROUP]))];\nconst values = rows.map((d) => d[SCORE]);\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[GROUP] === group).map((d) => d[SCORE]);\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, mean: groupValues.reduce((s, v) => s + v, 0) / groupValues.length };\n});\nconst yMax = Math.max(...groupStats.flatMap((g) => g.counts)) * (1 + Y_HEADROOM_SHARE);\n// A mean below the average of all group means is labelled left of its line, the others right\nconst meanOfMeans = groupStats.reduce((s, g) => s + g.mean, 0) / groupStats.length;\n\nconst TITLE = \"histogram-overlapping · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${groupStats.map((g) => `${g.group} n = ${g.n}`).join(\" · \")} · shared bin width ${binWidth} · dashed lines: group means`;\nconst COUNT_LABEL = \"Frequency (count per bin)\";\nconst HEADER_H = 76;\nconst LEGEND_H = 44;\n\n// Group means at their exact value: with contiguous bins the band axis is linear in value\nfunction MeanLines() {\n  const xScale = useXScale() as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const { top, height } = useDrawingArea();\n  const pxPerUnit = xScale.bandwidth() / binWidth;\n  const x0 = xScale(binLabels[0]);\n  return (\n    <g>\n      {groupStats.map((g, i) => {\n        const x = x0 + (g.mean - binStart) * pxPerUnit;\n        const flip = g.mean < meanOfMeans;\n        return (\n          <g key={g.group}>\n            <line x1={x} x2={x} y1={top} y2={top + height} stroke={t.palette[i]} strokeWidth={2.5} strokeDasharray=\"7 5\" />\n            <text\n              x={flip ? x - 8 : x + 8}\n              y={top + 20 + i * 24}\n              textAnchor={flip ? \"end\" : \"start\"}\n              fontSize={15}\n              fontWeight={600}\n              fill={t.ink}\n            >\n              {`${g.group} mean ${g.mean.toFixed(1)}`}\n            </text>\n          </g>\n        );\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\", 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: 16, left: 24 }}\n        series={groupStats.map((g, i) => ({\n          id: `group-${i}`,\n          data: g.counts,\n          label: g.group,\n          color: `${t.palette[i]}${FILL_ALPHA_HEX}`,\n          highlightScope: { highlight: \"series\", fade: \"global\" },\n        }))}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: binLabels,\n            categoryGapRatio: 0,\n            // Overlap the groups instead of placing them side by side: a gap ratio\n            // of -1 gives every series the full band width at the same offset\n            barGapRatio: -1,\n            height: 64,\n            label: SCORE,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: yMax,\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: \"top\", horizontal: \"end\" },\n            sx: { fontSize: 15, color: t.ink, pr: \"40px\", gap: \"24px\" },\n          },\n        }}\n        sx={{ \"& .MuiChartsGrid-line\": { stroke: t.grid } }}\n      >\n        <MeanLines />\n      </BarChart>\n    </Box>\n  );\n}\n"}