{"spec_id":"violin-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// violin-basic: Basic Violin Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-23\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;\nconst TITLE = \"violin-basic · javascript · muix · anyplot.ai\";\nconst TITLE_HEIGHT = 56;\n\n// Constants\nconst GRID_N = 140; // KDE evaluation points per violin\nconst TAIL_BANDWIDTHS = 1.5; // the density falls below ~4 % of its peak this far past the data\n\n// Columns: set these to your data's column names\nconst CLASS_GROUP = \"Class group\"; // role: category\nconst SCORE = \"Exam score (%)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Exam scores for four class groups, each shaped differently so the density\n// carries what a box plot would hide: unimodal, narrow, bimodal, skewed.\nlet seed = 42;\nconst rand = () => (seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296;\nconst normal = (mean, sd) => mean + sd * Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\nconst groupShapes = [\n  [\"Group A\", () => normal(74, 8)],\n  [\"Group B\", () => normal(88, 3.5)],\n  [\"Group C\", () => (rand() < 0.45 ? normal(62, 5) : normal(82, 4))],\n  [\"Group D\", () => 90 - 28 * Math.pow(rand(), 2.4) + normal(0, 2)],\n];\nconst data = groupShapes.flatMap(([group, draw]) =>\n  Array.from({ length: 220 }, () => {\n    let score = draw();\n    while (score < 50 || score > 99) score = draw(); // redraw out-of-range scores\n    return { [CLASS_GROUP]: group, [SCORE]: Math.round(score * 10) / 10 };\n  }),\n);\n\n// Plot: reads only data and the constants above\nconst categories = [...new Set(data.map((d) => d[CLASS_GROUP]))];\n\n// Per group: Tukey box stats and a Gaussian KDE (Silverman bandwidth) normalized\n// to its own peak. The grid ends a short way past the data, where the density\n// is nearly zero, and the outline closes to a point there, so each violin\n// tapers just beyond its data instead of being cut flat.\nconst violins = categories.map((cat) => {\n  const values = data\n    .filter((d) => d[CLASS_GROUP] === cat && d[SCORE] != null)\n    .map((d) => d[SCORE])\n    .sort((a, b) => a - b);\n  const n = values.length;\n  const quantile = (q) => {\n    const pos = (n - 1) * q;\n    const base = Math.floor(pos);\n    return values[base] + (pos - base) * ((values[base + 1] ?? values[base]) - values[base]);\n  };\n  const [q1, median, q3] = [0.25, 0.5, 0.75].map(quantile);\n  const inliers = values.filter((v) => v >= q1 - 1.5 * (q3 - q1) && v <= q3 + 1.5 * (q3 - q1));\n\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) / (n - 1));\n  const bandwidth = 0.9 * sd * Math.pow(n, -0.2);\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\n  return {\n    cat,\n    q1,\n    median,\n    q3,\n    whiskerLow: inliers[0],\n    whiskerHigh: inliers[inliers.length - 1],\n    grid,\n    density: raw.map((v) => v / peak),\n  };\n});\n\nconst gridMin = Math.min(...violins.map((v) => v.grid[0]));\nconst gridMax = Math.max(...violins.map((v) => v.grid[GRID_N - 1]));\nconst yPad = (gridMax - gridMin) * 0.03;\n\n// The community package has no violin component: a custom SVG layer placed\n// through the chart's own band/linear scales draws one inside ChartsContainer.\nfunction Violins() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const band = xScale.bandwidth();\n  const violinHalfWidth = band * 0.44;\n  const boxHalfWidth = Math.min(16, band * 0.09);\n\n  return (\n    <g>\n      {violins.map(({ cat, grid, density, q1, median, q3, whiskerLow, whiskerHigh }, i) => {\n        const color = t.palette[i];\n        const center = xScale(cat) + band / 2;\n        const leftSide = grid.map((gy, k) => `${center - density[k] * violinHalfWidth},${yScale(gy)}`);\n        const rightSide = grid.map((gy, k) => `${center + density[k] * violinHalfWidth},${yScale(gy)}`).reverse();\n        const bottomTip = `${center},${yScale(grid[0])}`;\n        const topTip = `${center},${yScale(grid[GRID_N - 1])}`;\n        const violinPath = `M${bottomTip} L${leftSide.join(\" L\")} L${topTip} L${rightSide.join(\" L\")} Z`;\n\n        return (\n          <g key={cat}>\n            <path\n              d={violinPath}\n              fill={color}\n              fillOpacity={0.5}\n              stroke={color}\n              strokeWidth={1.75}\n              strokeLinejoin=\"round\"\n            />\n            <line x1={center} x2={center} y1={yScale(whiskerLow)} y2={yScale(whiskerHigh)} stroke={t.ink} strokeWidth={1.5} />\n            <rect\n              x={center - boxHalfWidth}\n              y={yScale(q3)}\n              width={boxHalfWidth * 2}\n              height={Math.max(1, yScale(q1) - yScale(q3))}\n              fill={t.ink}\n              rx={3}\n            />\n            <line\n              x1={center - boxHalfWidth}\n              x2={center + boxHalfWidth}\n              y1={yScale(median)}\n              y2={yScale(median)}\n              stroke={t.pageBg}\n              strokeWidth={2.5}\n            />\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const chartHeight = window.ANYPLOT_SIZE.height - TITLE_HEIGHT;\n\n  return (\n    <div style={{ width: window.ANYPLOT_SIZE.width, height: window.ANYPLOT_SIZE.height }}>\n      <div\n        style={{\n          height: TITLE_HEIGHT,\n          lineHeight: `${TITLE_HEIGHT}px`,\n          paddingLeft: 24,\n          fontSize: 22,\n          fontWeight: 500,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsContainer\n        width={window.ANYPLOT_SIZE.width}\n        height={chartHeight}\n        series={[]}\n        skipAnimation\n        margin={{ top: 32, right: 50, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            id: \"groups\",\n            data: categories,\n            scaleType: \"band\",\n            height: 76,\n            label: CLASS_GROUP,\n            labelStyle: { fontSize: 16 },\n            tickLabelStyle: { fontSize: 16 },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"scores\",\n            min: gridMin - yPad,\n            max: gridMax + yPad,\n            width: 84,\n            label: SCORE,\n            labelStyle: { fontSize: 16 },\n            tickLabelStyle: { fontSize: 14 },\n          },\n        ]}\n      >\n        <ChartsGrid\n          horizontal\n          sx={{\n            \"& .MuiChartsGrid-line\": {\n              stroke: t.grid,\n              opacity: 0.2,\n            },\n          }}\n        />\n        <Violins />\n        <ChartsXAxis axisId=\"groups\" disableTicks />\n        <ChartsYAxis axisId=\"scores\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}