{"spec_id":"box-grouped","library":"muix","language":"javascript","code":"// anyplot.ai\n// box-grouped: Grouped Box Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst IQR_FENCE_MULTIPLIER = 1.5;\nconst Y_PAD_SHARE = 0.08;\nconst GROUP_WIDTH_SHARE = 0.84;\nconst BOX_SLOT_SHARE = 0.72;\nconst BOX_FILL_ALPHA = 0.32;\nconst BOX_STROKE_PX = 2.2;\nconst HEADER_H = 106;\n\n// Columns: set these to your data's column names\nconst CATEGORY = \"Department\"; // role: category\nconst SUBCATEGORY = \"Experience level\"; // role: subcategory\nconst VALUE = \"Productivity index (0–100)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let state = 42;\n  const depts = [\"Engineering\", \"Sales\", \"Marketing\", \"Customer Support\"];\n  const lvls = [\"Junior\", \"Mid-Level\", \"Senior\"];\n  const lvlParams: { [key: string]: { mean: number; std: number } } = {\n    Junior: { mean: 52, std: 9 },\n    \"Mid-Level\": { mean: 68, std: 8 },\n    Senior: { mean: 82, std: 7 },\n  };\n  const deptOffsets: { [key: string]: number } = {\n    Engineering: 5,\n    Sales: -4,\n    Marketing: 2,\n    \"Customer Support\": -6,\n  };\n  const sampleCount = 46;\n  const rows: { [key: string]: string | number }[] = [];\n\n  for (let di = 0; di < depts.length; di += 1) {\n    const dept = depts[di];\n    for (let li = 0; li < lvls.length; li += 1) {\n      const lvl = lvls[li];\n      const { mean, std } = lvlParams[lvl];\n      const offset = deptOffsets[dept];\n      for (let i = 0; i < sampleCount; i += 1) {\n        state = (state * 1664525 + 1013904223) >>> 0;\n        const u1 = Math.max(state / 4294967296, 1e-9);\n        state = (state * 1664525 + 1013904223) >>> 0;\n        const u2 = state / 4294967296;\n        const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n        const val = Math.min(100, Math.max(0, mean + offset + z * std));\n        rows.push({\n          [CATEGORY]: dept,\n          [SUBCATEGORY]: lvl,\n          [VALUE]: Number(val.toFixed(2)),\n        });\n      }\n      if ((di + li) % 2 === 0) {\n        const outlierVal = Math.min(100, Math.max(0, mean + offset + 3.4 * std));\n        rows.push({\n          [CATEGORY]: dept,\n          [SUBCATEGORY]: lvl,\n          [VALUE]: Number(outlierVal.toFixed(2)),\n        });\n      }\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst categories: string[] = [];\nconst subcategories: string[] = [];\nfor (const row of data) {\n  const c = String(row[CATEGORY]);\n  const s = String(row[SUBCATEGORY]);\n  if (!categories.includes(c)) categories.push(c);\n  if (!subcategories.includes(s)) subcategories.push(s);\n}\n\nconst boxGroups = categories.map((cat) => ({\n  category: cat,\n  boxes: subcategories.map((sub) => {\n    const sorted = data\n      .filter(\n        (row) => String(row[CATEGORY]) === cat && String(row[SUBCATEGORY]) === sub,\n      )\n      .map((row) => Number(row[VALUE]))\n      .sort((a, b) => a - b);\n    const n = sorted.length;\n    if (n === 0) {\n      return { subcategory: sub, stats: null };\n    }\n\n    const [q1, median, q3] = [0.25, 0.5, 0.75].map((p) => {\n      const pos = (n - 1) * p;\n      const base = Math.floor(pos);\n      return base + 1 < n\n        ? sorted[base] + (pos - base) * (sorted[base + 1] - sorted[base])\n        : sorted[base];\n    });\n\n    const iqr = q3 - q1;\n    const lowerFence = q1 - IQR_FENCE_MULTIPLIER * iqr;\n    const upperFence = q3 + IQR_FENCE_MULTIPLIER * iqr;\n    const inliers = sorted.filter((v) => v >= lowerFence && v <= upperFence);\n    const outliers = sorted.filter((v) => v < lowerFence || v > upperFence);\n\n    return {\n      subcategory: sub,\n      stats: {\n        q1,\n        median,\n        q3,\n        whiskerMin: inliers[0],\n        whiskerMax: inliers[inliers.length - 1],\n        outliers,\n      },\n    };\n  }),\n}));\n\nconst allValues = data.map((row) => Number(row[VALUE]));\nconst dataMin = Math.min(...allValues);\nconst dataMax = Math.max(...allValues);\nconst valSpan = dataMax - dataMin || 1;\nconst yMin = dataMin - valSpan * Y_PAD_SHARE;\nconst yMax = dataMax + valSpan * Y_PAD_SHARE;\n\n// Ordered subcategories: evenly spaced steps of the imprint_seq ramp, in order\nconst hexToRgb = (hex: string) =>\n  [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));\nconst [seqStart, seqEnd] = [hexToRgb(t.seq[0]), hexToRgb(t.seq[1])];\nconst subColors = subcategories.map((_, i) => {\n  const f = subcategories.length > 1 ? i / (subcategories.length - 1) : 0;\n  const rgb = seqStart.map((c, k) => Math.round(c + f * (seqEnd[k] - c)));\n  return `#${rgb.map((c) => c.toString(16).padStart(2, \"0\")).join(\"\")}`;\n});\n\nconst TITLE = \"box-grouped · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length} observations · ${CATEGORY}: ${categories.length} · ${SUBCATEGORY}: ${subcategories.length} · Whiskers at ${IQR_FENCE_MULTIPLIER}×IQR`;\n\nfunction BoxWhiskerLayer() {\n  const xScale = useXScale(\"dept\");\n  const yScale = useYScale(\"val\");\n  const bandwidth = xScale.bandwidth();\n  const groupWidth = bandwidth * GROUP_WIDTH_SHARE;\n  const boxSlot = groupWidth / subcategories.length;\n  const boxWidth = boxSlot * BOX_SLOT_SHARE;\n  const capWidth = boxWidth * 0.62;\n\n  return (\n    <g>\n      {boxGroups.map((group) => {\n        const groupStart = xScale(group.category) + (bandwidth - groupWidth) / 2;\n        return group.boxes.map((box, subIdx) => {\n          if (!box.stats) return null;\n          const cx = groupStart + boxSlot * (subIdx + 0.5);\n          const color = subColors[subIdx];\n          const yQ1 = yScale(box.stats.q1);\n          const yQ3 = yScale(box.stats.q3);\n          const yMedian = yScale(box.stats.median);\n          const yWhiskerHigh = yScale(box.stats.whiskerMax);\n          const yWhiskerLow = yScale(box.stats.whiskerMin);\n          return (\n            <g key={`${group.category}-${box.subcategory}`}>\n              <line\n                x1={cx}\n                x2={cx}\n                y1={yWhiskerHigh}\n                y2={yQ3}\n                stroke={color}\n                strokeWidth={2}\n                strokeLinecap=\"round\"\n              />\n              <line\n                x1={cx}\n                x2={cx}\n                y1={yQ1}\n                y2={yWhiskerLow}\n                stroke={color}\n                strokeWidth={2}\n                strokeLinecap=\"round\"\n              />\n              <line\n                x1={cx - capWidth / 2}\n                x2={cx + capWidth / 2}\n                y1={yWhiskerHigh}\n                y2={yWhiskerHigh}\n                stroke={color}\n                strokeWidth={2}\n                strokeLinecap=\"round\"\n              />\n              <line\n                x1={cx - capWidth / 2}\n                x2={cx + capWidth / 2}\n                y1={yWhiskerLow}\n                y2={yWhiskerLow}\n                stroke={color}\n                strokeWidth={2}\n                strokeLinecap=\"round\"\n              />\n              <rect\n                x={cx - boxWidth / 2}\n                y={yQ3}\n                width={boxWidth}\n                height={Math.max(yQ1 - yQ3, 1)}\n                rx={3}\n                fill={color}\n                fillOpacity={BOX_FILL_ALPHA}\n                stroke={color}\n                strokeWidth={BOX_STROKE_PX}\n              />\n              <line\n                x1={cx - boxWidth / 2}\n                x2={cx + boxWidth / 2}\n                y1={yMedian}\n                y2={yMedian}\n                stroke={color}\n                strokeWidth={3.5}\n                strokeLinecap=\"round\"\n              />\n              {box.stats.outliers.map((value, outlierIndex) => (\n                <circle\n                  key={outlierIndex}\n                  cx={cx}\n                  cy={yScale(value)}\n                  r={5}\n                  fill={t.pageBg}\n                  stroke={color}\n                  strokeWidth={2}\n                />\n              ))}\n            </g>\n          );\n        });\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const chartWidth = window.ANYPLOT_SIZE.width;\n  const chartHeight = window.ANYPLOT_SIZE.height - HEADER_H;\n\n  return (\n    <div\n      style={{\n        width: chartWidth,\n        height: window.ANYPLOT_SIZE.height,\n        background: t.pageBg,\n        fontFamily: \"Inter, system-ui, sans-serif\",\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 28 }}>\n          {subcategories.map((sub, i) => (\n            <div\n              key={sub}\n              style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}\n            >\n              <svg width=\"16\" height=\"16\" style={{ display: \"inline-block\" }}>\n                <rect\n                  x={BOX_STROKE_PX / 2}\n                  y={BOX_STROKE_PX / 2}\n                  width={16 - BOX_STROKE_PX}\n                  height={16 - BOX_STROKE_PX}\n                  rx={3}\n                  fill={subColors[i]}\n                  fillOpacity={BOX_FILL_ALPHA}\n                  stroke={subColors[i]}\n                  strokeWidth={BOX_STROKE_PX}\n                />\n              </svg>\n              <span style={{ fontSize: 14, color: t.inkSoft }}>{sub}</span>\n            </div>\n          ))}\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={chartWidth}\n        height={chartHeight}\n        series={[]}\n        skipAnimation\n        margin={{ top: 20, right: 40, bottom: 20, left: 40 }}\n        xAxis={[\n          {\n            id: \"dept\",\n            scaleType: \"band\",\n            data: categories,\n            categoryGapRatio: 0.36,\n            height: 64,\n            label: CATEGORY,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"val\",\n            min: yMin,\n            max: yMax,\n            tickNumber: 9,\n            width: 84,\n            label: VALUE,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": {\n            stroke: t.grid,\n            opacity: 0.7,\n            strokeDasharray: \"3 4\",\n          },\n        }}\n      >\n        <ChartsGrid horizontal />\n        <BoxWhiskerLayer />\n        <ChartsXAxis axisId=\"dept\" />\n        <ChartsYAxis axisId=\"val\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}