{"spec_id":"violin-grouped-swarm","library":"muix","language":"javascript","code":"// anyplot.ai\n// violin-grouped-swarm: Grouped Violin Plot with Swarm Overlay\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\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, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst GRID_N = 120; // KDE evaluation points per violin\nconst TAIL_BANDWIDTHS = 1.5; // the density falls below ~4 % of its peak this far past the data\nconst Y_PAD = 0.06; // share of the value range added below the data\nconst Y_HEADROOM = 0.12; // share of the value range added above the data, room for the callout\nconst GROUP_SPAN = 0.84; // share of a category band the violins of its groups fill\nconst MARKER_R = 4; // swarm point radius, px\nconst TITLE = \"violin-grouped-swarm · javascript · muix · anyplot.ai\";\nconst TITLE_H = 80;\nconst LEGEND_H = 40;\n\n// Columns: set these to your data's column names\nconst TASK = \"Task type\"; // role: category\nconst LEVEL = \"Agent level\"; // role: group\nconst TIME = \"Resolution time (s)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Support-ticket resolution times, 40 tickets per task type and agent level.\n// Junior agents run slower and more variably than seniors, except on code\n// review, where both lean on the same checklist and the gap nearly closes.\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 cells = [\n    [\"Bug Triage\", \"Junior\", 95, 24],\n    [\"Bug Triage\", \"Senior\", 52, 12],\n    [\"Data Entry\", \"Junior\", 60, 16],\n    [\"Data Entry\", \"Senior\", 38, 9],\n    [\"Code Review\", \"Junior\", 130, 22],\n    [\"Code Review\", \"Senior\", 118, 20],\n  ];\n  return cells.flatMap(([task, level, mean, sd]) =>\n    Array.from({ length: 40 }, () => ({\n      [TASK]: task,\n      [LEVEL]: level,\n      [TIME]: Math.round(Math.min(220, Math.max(10, mean + sd * gaussian())) * 10) / 10,\n    })),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[TIME] != null);\nconst categories = [...new Set(rows.map((d) => d[TASK]))];\nconst groups = [...new Set(rows.map((d) => d[LEVEL]))];\n\n// Per category and group: sorted values, median and a Gaussian KDE (Silverman\n// bandwidth) normalized to its own peak on a grid that ends a short way past\n// the data, so each violin tapers just beyond its values. Empty cells stay null.\nconst cells = categories.map((cat) =>\n  groups.map((group) => {\n    const values = rows\n      .filter((d) => d[TASK] === cat && d[LEVEL] === group)\n      .map((d) => d[TIME])\n      .sort((a, b) => a - b);\n    const n = values.length;\n    if (n === 0) return null;\n    const median = n % 2 === 0 ? (values[n / 2 - 1] + values[n / 2]) / 2 : values[(n - 1) / 2];\n    const mean = values.reduce((a, b) => a + b, 0) / n;\n    const sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, n - 1));\n    const bandwidth = Math.max(0.9 * sd * Math.pow(n, -0.2), 1e-6);\n    const lo = values[0] - TAIL_BANDWIDTHS * bandwidth;\n    const hi = values[n - 1] + TAIL_BANDWIDTHS * bandwidth;\n    const grid = Array.from({ length: GRID_N }, (_, k) => lo + (k * (hi - lo)) / (GRID_N - 1));\n    const raw = grid.map((gy) => values.reduce((sum, v) => sum + Math.exp(-0.5 * ((gy - v) / bandwidth) ** 2), 0));\n    const peak = Math.max(...raw);\n    return { values, median, grid, density: raw.map((v) => v / peak) };\n  }),\n);\n\nconst filled = cells.flat().filter((c) => c != null);\nconst gridMin = Math.min(...filled.map((c) => c.grid[0]));\nconst gridMax = Math.max(...filled.map((c) => c.grid[GRID_N - 1]));\nconst yMin = gridMin - (gridMax - gridMin) * Y_PAD;\nconst yMax = gridMax + (gridMax - gridMin) * Y_HEADROOM;\n\n// Focal callout: the category whose group medians lie closest together\nconst UNIT = TIME.match(/\\(([^)]+)\\)\\s*$/)?.[1] ?? \"\";\nconst medianSpread = cells.map((row) => {\n  const medians = row.filter((c) => c != null).map((c) => c.median);\n  return medians.length > 1 ? Math.max(...medians) - Math.min(...medians) : null;\n});\nconst closestIndex = groups.length > 1\n  ? medianSpread.reduce((best, s, i) => (s != null && (best < 0 || s < medianSpread[best]) ? i : best), -1)\n  : -1;\nconst CALLOUT = closestIndex >= 0 ? `Closest medians: ${medianSpread[closestIndex].toFixed(1)} ${UNIT} apart` : null;\nconst SUBTITLE = `${rows.length} observations, ${categories.length} ${TASK.toLowerCase()}s × ${groups.length} ${LEVEL.toLowerCase()}s · line: median`;\n\n// The community package has no violin or swarm component: a custom layer\n// draws them through the chart's band and linear scales, the groups dodged\n// side by side inside each category band.\nfunction GroupedViolinSwarm() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const { top } = useDrawingArea();\n  const band = xScale.bandwidth();\n  const slot = (band * GROUP_SPAN) / groups.length;\n  const violinHalfWidth = slot * 0.44;\n  const swarmHalfWidth = slot * 0.4;\n  const diameter = MARKER_R * 2 + 1;\n  const step = diameter * 0.92;\n  const maxK = Math.max(1, Math.floor(swarmHalfWidth / step));\n\n  return (\n    <g>\n      {categories.map((cat, ci) => {\n        const start = xScale(cat) + (band * (1 - GROUP_SPAN)) / 2;\n        const centersX = groups.map((_, gi) => start + slot * (gi + 0.5));\n        const tops = cells[ci].filter((c) => c != null).map((c) => yScale(c.grid[GRID_N - 1]));\n        return (\n          <g key={cat}>\n            {groups.map((group, gi) => {\n              const cell = cells[ci][gi];\n              if (cell == null) return null;\n              const color = t.palette[gi];\n              const cx = centersX[gi];\n              const leftSide = cell.grid.map((gy, k) => `${cx - cell.density[k] * violinHalfWidth},${yScale(gy)}`);\n              const rightSide = cell.grid.map((gy, k) => `${cx + cell.density[k] * violinHalfWidth},${yScale(gy)}`).reverse();\n              const violinPath = `M${cx},${yScale(cell.grid[0])} L${leftSide.join(\" L\")} L${cx},${yScale(cell.grid[GRID_N - 1])} L${rightSide.join(\" L\")} Z`;\n\n              // Beeswarm: each point keeps its value; it moves sideways only as\n              // far as needed to clear the points already placed near it, or,\n              // where the row is full, to the offset that overlaps them least.\n              const swarm = [];\n              cell.values.forEach((v) => {\n                const y = yScale(v);\n                const nearby = swarm.filter((p) => Math.abs(y - p.y) < diameter);\n                let offset = null;\n                let fallback = { offset: 0, gap: -Infinity };\n                for (let k = 0; k <= 2 * maxK && offset == null; k += 1) {\n                  const candidate = (k % 2 === 1 ? 1 : -1) * Math.ceil(k / 2) * step;\n                  const gap = Math.min(Infinity, ...nearby.map((p) => Math.hypot(candidate - p.offset, y - p.y)));\n                  if (gap >= diameter * 0.95) offset = candidate;\n                  else if (gap > fallback.gap) fallback = { offset: candidate, gap };\n                }\n                swarm.push({ y, offset: offset ?? fallback.offset });\n              });\n\n              return (\n                <g key={`${cat}-${group}`}>\n                  <path d={violinPath} fill={color} fillOpacity={0.4} stroke={color} strokeWidth={1.75} strokeLinejoin=\"round\" />\n                  {swarm.map((p, i) => (\n                    <circle key={i} cx={cx + p.offset} cy={p.y} r={MARKER_R} fill={color} fillOpacity={0.9} stroke={t.pageBg} strokeWidth={0.75} />\n                  ))}\n                  <line\n                    x1={cx - violinHalfWidth * 0.8}\n                    x2={cx + violinHalfWidth * 0.8}\n                    y1={yScale(cell.median)}\n                    y2={yScale(cell.median)}\n                    stroke={t.ink}\n                    strokeWidth={2.5}\n                  />\n                </g>\n              );\n            })}\n            {ci === closestIndex && (\n              <g>\n                <line x1={centersX[0]} x2={centersX[groups.length - 1]} y1={Math.min(...tops) - 18} y2={Math.min(...tops) - 18} stroke={t.inkSoft} strokeWidth={1.25} />\n                {[centersX[0], centersX[groups.length - 1]].map((x) => (\n                  <line key={x} x1={x} x2={x} y1={Math.min(...tops) - 18} y2={Math.min(...tops) - 10} stroke={t.inkSoft} strokeWidth={1.25} />\n                ))}\n                <text\n                  x={(centersX[0] + centersX[groups.length - 1]) / 2}\n                  y={Math.max(top + 16, Math.min(...tops) - 28)}\n                  textAnchor=\"middle\"\n                  fontSize={15}\n                  fontStyle=\"italic\"\n                  fill={t.inkSoft}\n                >\n                  {CALLOUT}\n                </text>\n              </g>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"18px 36px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>{SUBTITLE}</div>\n      </div>\n      <div style={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", gap: 28, padding: \"0 36px\" }}>\n        <span style={{ fontSize: 15, color: t.ink }}>{LEVEL}</span>\n        {groups.map((group, i) => (\n          <div key={group} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span style={{ width: 14, height: 14, borderRadius: 7, background: t.palette[i], display: \"inline-block\" }} />\n            <span style={{ fontSize: 15, color: t.ink }}>{group}</span>\n          </div>\n        ))}\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        series={[]}\n        skipAnimation\n        margin={{ top: 8, right: 48, bottom: 12, left: 24 }}\n        xAxis={[\n          {\n            id: \"category\",\n            scaleType: \"band\",\n            data: categories,\n            categoryGapRatio: 0.3,\n            disableTicks: true,\n            height: 72,\n            label: TASK,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"value\",\n            min: yMin,\n            max: yMax,\n            width: 84,\n            label: TIME,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <ChartsGrid horizontal />\n        <GroupedViolinSwarm />\n        <ChartsXAxis axisId=\"category\" />\n        <ChartsYAxis axisId=\"value\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}