{"spec_id":"frequency-polygon-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// frequency-polygon-basic: Frequency Polygon for Distribution Comparison\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst BIN_COUNT = 18; // shared bins across the pooled range of every group\nconst X_PAD_SHARE = 0.015; // x padding beyond the closing vertices, as a share of their span\nconst FREQUENCY_LABEL = \"Frequency (count per bin)\";\nconst TITLE = \"frequency-polygon-basic · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\n\n// Columns: set these to your data's column names\nconst REACTION_TIME = \"Reaction time (ms)\"; // role: values\nconst CONDITION = \"Condition\"; // role: group\n\n// Data: replace this block with your own records, one object per row\n// Simple visual-stimulus reaction times, 300 trials per condition in a psychology lab study;\n// the sleep-deprived condition mixes in attentional lapses (microsleeps) that pull out a second mode.\nconst data = (() => {\n  const conditions = [\n    { label: \"Control\", seed: 11, components: [{ weight: 1, mean: 320, sd: 40 }] },\n    { label: \"Caffeine\", seed: 23, components: [{ weight: 1, mean: 280, sd: 35 }] },\n    {\n      label: \"Sleep-deprived\",\n      seed: 37,\n      components: [\n        { weight: 0.68, mean: 350, sd: 35 },\n        { weight: 0.32, mean: 475, sd: 45 },\n      ],\n    },\n  ];\n  return conditions.flatMap((condition) => {\n    let state = condition.seed;\n    const rand = () => {\n      state = (state * 1664525 + 1013904223) % 4294967296;\n      return state / 4294967296;\n    };\n    return Array.from({ length: 300 }, () => {\n      const pick = rand();\n      let cumulative = 0;\n      const component =\n        condition.components.find((c) => (cumulative += c.weight) >= pick) ??\n        condition.components[condition.components.length - 1];\n      const u1 = Math.max(rand(), 1e-9);\n      const u2 = rand();\n      const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n      return { [CONDITION]: condition.label, [REACTION_TIME]: Math.max(150, component.mean + z * component.sd) };\n    });\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst observations = data.filter((d) => Number.isFinite(d[REACTION_TIME]));\nconst conditions = [...new Set(observations.map((d) => d[CONDITION]))];\n\n// Bin edges shared by every group, so the vertices of all polygons sit at the same x positions\nconst valueMin = Math.min(...observations.map((d) => d[REACTION_TIME]));\nconst valueMax = Math.max(...observations.map((d) => d[REACTION_TIME]));\nconst binWidth = (valueMax - valueMin) / BIN_COUNT;\n\n// One vertex per bin midpoint, plus one empty bin at each end so every polygon closes on zero\nconst midpoints = Array.from({ length: BIN_COUNT + 2 }, (_, i) => valueMin + (i - 0.5) * binWidth);\nconst frequencies = conditions.map((condition) => {\n  const counts = new Array(BIN_COUNT + 2).fill(0);\n  observations\n    .filter((d) => d[CONDITION] === condition)\n    .forEach((d) => {\n      counts[1 + Math.min(BIN_COUNT - 1, Math.floor((d[REACTION_TIME] - valueMin) / binWidth))] += 1;\n    });\n  return counts;\n});\n\nconst unit = REACTION_TIME.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst subtitle = `n = ${observations.length} across ${conditions.length} groups · ${BIN_COUNT} shared bins of ${binWidth.toFixed(1)} ${unit}`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <Box sx={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, pt: \"20px\", px: \"40px\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, mt: \"6px\" }}>{subtitle}</Typography>\n      </Box>\n      <LineChart\n        width={width}\n        height={height - TITLE_H - 48}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 16, right: 48, bottom: 8, left: 24 }}\n        xAxis={[\n          {\n            data: midpoints,\n            scaleType: \"linear\",\n            min: midpoints[0] - X_PAD_SHARE * (midpoints[midpoints.length - 1] - midpoints[0]),\n            max: midpoints[midpoints.length - 1] + X_PAD_SHARE * (midpoints[midpoints.length - 1] - midpoints[0]),\n            label: REACTION_TIME,\n            height: 68,\n            tickNumber: 10,\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            label: FREQUENCY_LABEL,\n            width: 84,\n            tickNumber: 8,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={conditions.map((condition, i) => ({\n          id: `condition-${i}`,\n          data: frequencies[i],\n          label: condition,\n          color: t.palette[i],\n          curve: \"linear\",\n          area: true,\n          showMark: true,\n          shape: \"circle\",\n        }))}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.inkSoft, mt: \"8px\" },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.14 },\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiLineChart-mark\": { strokeWidth: 2 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      />\n    </Box>\n  );\n}\n"}