{"spec_id":"histogram-stepwise","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-stepwise: Step Histogram\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\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 BIN_COUNT = 26; // shared bins across the pooled range of all groups\nconst Y_HEADROOM_SHARE = 0.16; // room above the tallest step for the peak labels\n\n// Columns: set these to your data's column names\nconst LATENCY = \"Response latency (ms)\"; // role: values\nconst VERSION = \"API version\"; // role: group\n\n// Data: replace this block with your own records, one object per observation\n// Response latency of 800 requests each before (v1) and after (v2) an\n// optimisation pass of the same API endpoint.\nconst data = (() => {\n  let state = 42 >>> 0;\n  const rng = () => {\n    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n    return state / 4294967296;\n  };\n  const versions = [\n    { name: \"API v1\", mean: 118, sd: 22 },\n    { name: \"API v2\", mean: 92, sd: 16 },\n  ];\n  return versions.flatMap((v) =>\n    Array.from({ length: 800 }, () => {\n      const z = Math.sqrt(-2 * Math.log(Math.max(rng(), 1e-9))) * Math.cos(2 * Math.PI * rng());\n      return { [VERSION]: v.name, [LATENCY]: Number(Math.max(8, v.mean + z * v.sd).toFixed(1)) };\n    }),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[LATENCY] != null);\nconst groups = [...new Set(rows.map((d) => d[VERSION]))];\nconst values = rows.map((d) => d[LATENCY]);\nconst minValue = Math.min(...values);\nconst maxValue = Math.max(...values);\nconst binWidth = (maxValue - minValue) / BIN_COUNT;\nconst edges = Array.from({ length: BIN_COUNT + 1 }, (_, i) => minValue + i * binWidth);\n\nconst groupStats = groups.map((group) => {\n  const counts = new Array(BIN_COUNT).fill(0);\n  const groupValues = rows.filter((d) => d[VERSION] === group).map((d) => d[LATENCY]);\n  for (const v of groupValues) counts[Math.min(BIN_COUNT - 1, Math.floor((v - minValue) / binWidth))] += 1;\n  const peakIndex = counts.indexOf(Math.max(...counts));\n  return { group, counts, n: groupValues.length, peak: (edges[peakIndex] + edges[peakIndex + 1]) / 2 };\n});\n// One x per bin edge with curve \"stepAfter\": the doubled first edge lifts the outline\n// from zero, and the trailing 0 closes it back to the axis at the last edge\nconst stepX = [edges[0], ...edges];\nconst yMax = Math.max(...groupStats.flatMap((g) => g.counts)) * (1 + Y_HEADROOM_SHARE);\n// A peak below the average of all peaks is labelled left of its line, the others right\nconst meanPeak = groupStats.reduce((s, g) => s + g.peak, 0) / groupStats.length;\n\nconst unit = LATENCY.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst unitSuffix = unit ? ` ${unit}` : \"\";\nconst TITLE = \"histogram-stepwise · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${groupStats.map((g) => `${g.group} n = ${g.n}`).join(\" · \")} · ${BIN_COUNT} shared bins of ${binWidth.toFixed(1)}${unitSuffix} · dashed lines: centre of each tallest bin`;\nconst COUNT_LABEL = \"Frequency (count per bin)\";\nconst HEADER_H = 76;\nconst LEGEND_H = 44;\n\n// Peak markers at the centre of each group's tallest bin\nfunction PeakLines() {\n  const xScale = useXScale() as (v: number) => number;\n  const { top, height } = useDrawingArea();\n  return (\n    <g>\n      {groupStats.map((g, i) => {\n        const x = xScale(g.peak);\n        const leftSide = g.peak < meanPeak;\n        return (\n          <g key={g.group}>\n            <line x1={x} x2={x} y1={top} y2={top + height} stroke={t.palette[i]} strokeWidth={2} strokeDasharray=\"6 4\" />\n            <text\n              x={leftSide ? x - 8 : x + 8}\n              y={top + 20 + i * 24}\n              textAnchor={leftSide ? \"end\" : \"start\"}\n              fontSize={15}\n              fontWeight={600}\n              fill={t.ink}\n            >\n              {`${g.group} peak ${g.peak.toFixed(0)}${unitSuffix}`}\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      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\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: [0, ...g.counts, 0],\n          label: g.group,\n          color: t.palette[i],\n          curve: \"stepAfter\",\n          showMark: false,\n        }))}\n        xAxis={[\n          {\n            data: stepX,\n            scaleType: \"linear\",\n            min: edges[0],\n            max: edges[edges.length - 1],\n            tickNumber: 12,\n            height: 64,\n            label: LATENCY,\n            valueFormatter: (v: number) => v.toFixed(0),\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={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <PeakLines />\n      </LineChart>\n    </Box>\n  );\n}\n"}