{"spec_id":"violin-swarm","library":"muix","language":"javascript","code":"// anyplot.ai\n// violin-swarm: Violin Plot with Overlaid Swarm Points\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst GRID_N = 140; // KDE evaluation points per violin\nconst TAIL_BANDWIDTHS = 2; // each violin ends this many bandwidths past its outermost value\nconst Y_PAD = 0.04; // share of the violins' value range added above and below them\nconst VIOLIN_SPAN = 0.8; // share of a category band the widest violin fills\nconst MARKER_R = 5; // swarm point radius, px\nconst TITLE = \"violin-swarm · javascript · muix · anyplot.ai\";\nconst TITLE_H = 80;\n\n// Columns: set these to your data's column names\nconst CONDITION = \"Condition\"; // role: category\nconst REACTION_TIME = \"Reaction time (ms)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Reaction times across four experimental conditions, 50 trials each. Each\n// condition has its own shape: sleep deprivation adds a cluster of attention\n// lapses (a second mode), and the dual task skews into a long slow tail.\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (state * 1664525 + 1013904223) % 4294967296;\n    return state / 4294967296;\n  };\n  const normal = (mean, sd) =>\n    mean + sd * Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const clamp = (v) => Math.min(650, Math.max(300, v));\n  const conditions = [\n    [\"Baseline\", () => clamp(normal(420, 35))],\n    [\"Caffeine\", () => clamp(normal(360, 28))],\n    [\"Sleep-deprived\", () => clamp(rand() < 0.75 ? normal(470, 30) : normal(590, 25))],\n    [\"Dual-task\", () => clamp(430 + 140 * Math.pow(rand(), 2.2) + 8 * normal(0, 1))],\n  ];\n  return conditions.flatMap(([name, sample]) =>\n    Array.from({ length: 50 }, () => ({ [CONDITION]: name, [REACTION_TIME]: Math.round(sample() * 10) / 10 })),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[REACTION_TIME] != null);\nconst categories = [...new Set(rows.map((d) => d[CONDITION]))];\n\n// Per category: sorted values, median and a Gaussian KDE (Silverman bandwidth)\n// normalized to its own peak, so width encodes shape rather than sample count.\n// The grid ends a few bandwidths past the data, so each violin tapers near its\n// own range.\nconst violins = categories.map((cat) => {\n  const values = rows\n    .filter((d) => d[CONDITION] === cat)\n    .map((d) => d[REACTION_TIME])\n    .sort((a, b) => a - b);\n  const n = values.length;\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  const density = raw.map((v) => v / peak);\n  const valueDensity = values.map(\n    (y) => values.reduce((sum, v) => sum + Math.exp(-0.5 * ((y - v) / bandwidth) ** 2), 0) / peak,\n  );\n  const medianDensity = values.reduce((sum, v) => sum + Math.exp(-0.5 * ((median - v) / bandwidth) ** 2), 0) / peak;\n\n  return { values, valueDensity, median, medianDensity, grid, density };\n});\nconst gridMin = Math.min(...violins.map((v) => v.grid[0]));\nconst gridMax = Math.max(...violins.map((v) => v.grid[GRID_N - 1]));\nconst yMin = gridMin - (gridMax - gridMin) * Y_PAD;\nconst yMax = gridMax + (gridMax - gridMin) * Y_PAD;\nconst SUBTITLE = `${rows.length} observations in ${categories.length} groups · bar: median`;\n\n// The community package has no violin or swarm component: a custom layer\n// draws both through the chart's band and linear scales.\nfunction ViolinSwarm() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const band = xScale.bandwidth();\n  const halfWidth = (band * VIOLIN_SPAN) / 2;\n  const diameter = MARKER_R * 2 + 1.5;\n  const step = diameter * 0.92;\n\n  return (\n    <g>\n      {categories.map((cat, i) => {\n        const v = violins[i];\n        const color = t.palette[i];\n        const center = xScale(cat) + band / 2;\n        const leftSide = v.grid.map((gy, k) => `${center - v.density[k] * halfWidth},${yScale(gy)}`);\n        const rightSide = v.grid.map((gy, k) => `${center + v.density[k] * halfWidth},${yScale(gy)}`).reverse();\n        const violinPath = `M${leftSide.join(\" L\")} L${rightSide.join(\" L\")} Z`;\n\n        // Beeswarm: each point keeps its value and moves sideways only as far\n        // as needed to clear the points placed near it, never past the violin's\n        // own outline at that value.\n        const swarm = [];\n        v.values.forEach((value, j) => {\n          const y = yScale(value);\n          const maxOffset = Math.max(0, v.valueDensity[j] * halfWidth - MARKER_R);\n          const nearby = swarm.filter((p) => Math.abs(y - p.y) < diameter);\n          let offset = 0;\n          for (let k = 0; k <= 2 * Math.floor(maxOffset / step); k += 1) {\n            const candidate = (k % 2 === 1 ? 1 : -1) * Math.ceil(k / 2) * step;\n            if (nearby.every((p) => Math.hypot(candidate - p.offset, y - p.y) >= diameter * 0.95)) {\n              offset = candidate;\n              break;\n            }\n          }\n          swarm.push({ y, offset });\n        });\n\n        const medianHalf = v.medianDensity * halfWidth * 0.85;\n\n        return (\n          <g key={cat}>\n            <path d={violinPath} fill={color} fillOpacity={0.38} stroke={color} strokeWidth={1.75} strokeLinejoin=\"round\" />\n            {swarm.map((p, k) => (\n              <circle\n                key={k}\n                cx={center + p.offset}\n                cy={p.y}\n                r={MARKER_R}\n                fill={t.ink}\n                fillOpacity={0.85}\n                stroke={t.pageBg}\n                strokeWidth={0.75}\n              />\n            ))}\n            <line\n              x1={center - medianHalf}\n              x2={center + medianHalf}\n              y1={yScale(v.median)}\n              y2={yScale(v.median)}\n              stroke={t.pageBg}\n              strokeWidth={3}\n              strokeLinecap=\"round\"\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      <ChartsContainer\n        width={width}\n        height={height - TITLE_H}\n        series={[]}\n        skipAnimation\n        margin={{ top: 16, right: 48, bottom: 12, left: 24 }}\n        xAxis={[\n          {\n            id: \"category\",\n            scaleType: \"band\",\n            data: categories,\n            disableTicks: true,\n            height: 72,\n            label: CONDITION,\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: REACTION_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        <ViolinSwarm />\n        <ChartsXAxis axisId=\"category\" />\n        <ChartsYAxis axisId=\"value\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}