{"spec_id":"density-rug","library":"muix","language":"javascript","code":"// anyplot.ai\n// density-rug: Density Plot with Rug Marks\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 { useXScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SILVERMAN = 0.9; // robust rule of thumb: bandwidth = 0.9 · min(sd, IQR / 1.34) · n^(-1/5)\nconst KDE_CUT = 2; // the curve extends this many bandwidths past the outermost observations\nconst GRID_POINTS = 240;\nconst RUG_LEN = 26; // px, one tick per observation at the foot of the curve\nconst RUG_OPACITY = 0.7;\nconst TITLE = \"density-rug · javascript · muix · anyplot.ai\";\nconst TITLE_H = 76;\n\n// Columns: set these to your data's column names\nconst PETAL_LENGTH = \"Petal length (cm)\"; // role: values\n\n// Data: replace this block with your own records, one object per row\n// Petal lengths of 140 wildflowers from two populations surveyed in the same meadow, merged into one sample\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    const u1 = Math.max(rand(), 1e-9);\n    const u2 = rand();\n    return mean + sd * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n  };\n  return [\n    ...Array.from({ length: 75 }, () => normal(4.2, 0.4)),\n    ...Array.from({ length: 65 }, () => normal(6.6, 0.5)),\n  ].map((v) => ({ [PETAL_LENGTH]: Math.round(v * 100) / 100 }));\n})();\n\n// Plot: reads only data and the constants above\nconst values = data.map((d) => d[PETAL_LENGTH]).filter((v) => Number.isFinite(v));\nconst sorted = [...values].sort((a, b) => a - b);\nconst n = values.length;\nconst mean = values.reduce((sum, v) => sum + v, 0) / n;\nconst sd = Math.sqrt(values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (n - 1));\n// Linear-interpolated quartiles for the IQR term of the bandwidth rule\nconst q1Pos = (n - 1) * 0.25;\nconst q3Pos = (n - 1) * 0.75;\nconst q1 = sorted[Math.floor(q1Pos)] + (sorted[Math.ceil(q1Pos)] - sorted[Math.floor(q1Pos)]) * (q1Pos % 1);\nconst q3 = sorted[Math.floor(q3Pos)] + (sorted[Math.ceil(q3Pos)] - sorted[Math.floor(q3Pos)]) * (q3Pos % 1);\nconst bandwidth = SILVERMAN * Math.min(sd, (q3 - q1) / 1.34) * n ** (-1 / 5);\n\n// Gaussian kernel density on an even grid; the area under the curve is 1\nconst gridStart = sorted[0] - KDE_CUT * bandwidth;\nconst gridEnd = sorted[n - 1] + KDE_CUT * bandwidth;\nconst grid = Array.from({ length: GRID_POINTS }, (_, i) => gridStart + ((gridEnd - gridStart) * i) / (GRID_POINTS - 1));\nconst density = grid.map(\n  (x) =>\n    values.reduce((sum, v) => sum + Math.exp(-0.5 * ((x - v) / bandwidth) ** 2), 0) /\n    (n * bandwidth * Math.sqrt(2 * Math.PI)),\n);\n\nconst unit = PETAL_LENGTH.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst subtitle = `n = ${n} · Gaussian kernel, bandwidth ${bandwidth.toFixed(2)} ${unit} (Silverman's robust rule) · one rug tick per observation`;\n\nfunction RugMarks() {\n  const xScale = useXScale();\n  const { top, height } = useDrawingArea();\n  const foot = top + height;\n  return (\n    <g>\n      {values.map((v, i) => (\n        <line\n          key={i}\n          x1={xScale(v)}\n          x2={xScale(v)}\n          y1={foot}\n          y2={foot - RUG_LEN}\n          stroke={t.palette[0]}\n          strokeWidth={2}\n          strokeOpacity={RUG_OPACITY}\n        />\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"22px 40px 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, marginTop: 6 }}>{subtitle}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - TITLE_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 20, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: grid,\n            scaleType: \"linear\",\n            min: gridStart,\n            max: gridEnd,\n            label: PETAL_LENGTH,\n            height: 68,\n            tickNumber: 10,\n            valueFormatter: (v) => v.toFixed(1),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            label: \"Probability density\",\n            width: 84,\n            tickNumber: 6,\n            valueFormatter: (v) => v.toFixed(2),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"density\",\n            data: density,\n            label: \"Probability density\",\n            color: t.palette[0],\n            area: true,\n            curve: \"monotoneX\",\n            showMark: false,\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.2 },\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <RugMarks />\n      </LineChart>\n    </div>\n  );\n}\n"}