{"spec_id":"contour-density","library":"muix","language":"javascript","code":"// anyplot.ai\n// contour-density: Density Contour Plot\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ScatterChart } from \"@mui/x-charts/ScatterChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LEVEL_FRACTIONS = [0.12, 0.28, 0.46, 0.65, 0.85]; // contour levels as shares of the peak density\nconst GRID_STEPS = 70; // density grid nodes per axis\nconst PAD_SHARE = 0.12; // plot extent beyond the points, as a share of each variable's range\nconst SILVERMAN = 1.06; // Silverman's rule of thumb: h = 1.06 · sd · n^(-1/5) per axis\n\n// Columns: set these to your data's column names\nconst DIAMETER = \"Outer diameter (mm)\"; // role: x\nconst WEIGHT = \"Weight (g)\"; // role: y\n\n// Data: replace this block with your own records, one object per part\n// Bearing quality control: 900 parts from an on-spec batch and 500 from a batch that drifted high on\n// both dimensions, diameter and weight correlated within each batch\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (1664525 * state + 1013904223) >>> 0;\n    return state / 4294967296;\n  };\n  const normal = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const batches = [\n    { n: 900, meanDiameter: 23.92, sdDiameter: 0.13, meanWeight: 45.6, sdWeight: 0.7, rho: 0.5 },\n    { n: 500, meanDiameter: 24.58, sdDiameter: 0.12, meanWeight: 48.4, sdWeight: 0.65, rho: 0.45 },\n  ];\n  return batches.flatMap((b) =>\n    Array.from({ length: b.n }, () => {\n      const z1 = normal();\n      const z2 = normal();\n      return {\n        [DIAMETER]: b.meanDiameter + b.sdDiameter * z1,\n        [WEIGHT]: b.meanWeight + b.sdWeight * (b.rho * z1 + Math.sqrt(1 - b.rho * b.rho) * z2),\n      };\n    }),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst points = data\n  .filter((d) => Number.isFinite(d[DIAMETER]) && Number.isFinite(d[WEIGHT]))\n  .map((d, i) => ({ id: i, x: d[DIAMETER], y: d[WEIGHT] }));\nconst n = points.length;\n\n// Per axis: padded extent and the Silverman bandwidth of a Gaussian kernel\nconst [xAxisStats, yAxisStats] = [points.map((p) => p.x), points.map((p) => p.y)].map((values) => {\n  const low = Math.min(...values);\n  const high = Math.max(...values);\n  const mean = values.reduce((a, b) => a + b, 0) / values.length;\n  const sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / (values.length - 1));\n  const pad = (high - low) * PAD_SHARE;\n  return { min: low - pad, max: high + pad, bandwidth: SILVERMAN * sd * values.length ** (-1 / 5) };\n});\n\n// Kernel density estimate on a regular grid, density[j][i] at (gridX[i], gridY[j])\nconst gridX = Array.from({ length: GRID_STEPS }, (_, i) => xAxisStats.min + (i / (GRID_STEPS - 1)) * (xAxisStats.max - xAxisStats.min));\nconst gridY = Array.from({ length: GRID_STEPS }, (_, j) => yAxisStats.min + (j / (GRID_STEPS - 1)) * (yAxisStats.max - yAxisStats.min));\nconst density = gridY.map((gy) =>\n  gridX.map((gx) => {\n    let sum = 0;\n    points.forEach((p) => {\n      const dx = (gx - p.x) / xAxisStats.bandwidth;\n      const dy = (gy - p.y) / yAxisStats.bandwidth;\n      sum += Math.exp(-0.5 * (dx * dx + dy * dy));\n    });\n    return sum / (2 * Math.PI * n * xAxisStats.bandwidth * yAxisStats.bandwidth);\n  }),\n);\nconst peakDensity = Math.max(...density.flat());\n\n// Marching triangles: each grid cell splits into four triangles around its centre, which resolves\n// saddles; per level, the segment where the density crosses it inside every triangle\nconst triangles: { x: number; y: number; z: number }[][] = [];\nfor (let j = 0; j < GRID_STEPS - 1; j += 1) {\n  for (let i = 0; i < GRID_STEPS - 1; i += 1) {\n    const [sw, se, ne, nw] = [\n      [i, j],\n      [i + 1, j],\n      [i + 1, j + 1],\n      [i, j + 1],\n    ].map(([ii, jj]) => ({ x: gridX[ii], y: gridY[jj], z: density[jj][ii] }));\n    const centre = { x: (sw.x + se.x) / 2, y: (sw.y + nw.y) / 2, z: (sw.z + se.z + ne.z + nw.z) / 4 };\n    triangles.push([sw, se, centre], [se, ne, centre], [ne, nw, centre], [nw, sw, centre]);\n  }\n}\nconst contours = LEVEL_FRACTIONS.map((fraction, k) => {\n  const level = fraction * peakDensity;\n  const segments: { x: number; y: number }[][] = [];\n  triangles.forEach((tri) => {\n    const inside = tri.map((p) => p.z >= level);\n    if (inside.every(Boolean) || !inside.some(Boolean)) return;\n    const segment: { x: number; y: number }[] = [];\n    tri.forEach((p, m) => {\n      const q = tri[(m + 1) % 3];\n      if (inside[m] !== inside[(m + 1) % 3]) {\n        const r = (level - p.z) / (q.z - p.z);\n        segment.push({ x: p.x + r * (q.x - p.x), y: p.y + r * (q.y - p.y) });\n      }\n    });\n    segments.push(segment);\n  });\n  // Sequential Imprint ramp t.seq[0] -> t.seq[1]: the strongest colour marks the highest density\n  const share = k / (LEVEL_FRACTIONS.length - 1);\n  const [low, high] = t.seq.map((hex: string) => [16, 8, 0].map((shift) => (parseInt(hex.slice(1), 16) >> shift) & 255));\n  const color = `rgb(${low.map((c: number, ch: number) => Math.round(c + (high[ch] - c) * share)).join(\", \")})`;\n  return { fraction, segments, color, strokeWidth: 2.5 + k * 0.7 };\n});\n\nconst TITLE = \"Bearing QC · contour-density · javascript · muix · anyplot.ai\";\nconst subtitle = `n = ${n.toLocaleString(\"en-US\")} · Gaussian KDE, Silverman bandwidths ${xAxisStats.bandwidth.toFixed(3)} and ${yAxisStats.bandwidth.toFixed(2)} · ${GRID_STEPS} × ${GRID_STEPS} grid`;\nconst HEADER_H = 92;\nconst LEGEND_W = 190;\n\nfunction ContourLines() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {contours.map((c) => (\n        <path\n          key={c.fraction}\n          d={c.segments.map(([a, b]) => `M${xScale(a.x)!.toFixed(1)},${yScale(a.y)!.toFixed(1)}L${xScale(b.x)!.toFixed(1)},${yScale(b.y)!.toFixed(1)}`).join(\"\")}\n          fill=\"none\"\n          stroke={c.color}\n          strokeWidth={c.strokeWidth}\n          strokeOpacity={0.92}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        />\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: HEADER_H, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", gap: \"6px\", px: \"40px\", pt: \"8px\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.3 }}>{subtitle}</Typography>\n      </Box>\n      <Box sx={{ display: \"flex\", flexDirection: \"row\" }}>\n        <ScatterChart\n          width={width - LEGEND_W}\n          height={height - HEADER_H}\n          skipAnimation\n          hideLegend\n          disableVoronoi\n          grid={{ horizontal: true, vertical: true }}\n          margin={{ top: 20, right: 24, bottom: 24, left: 24 }}\n          series={[{ id: \"parts\", type: \"scatter\", data: points, color: t.inkSoft, markerSize: 3 }]}\n          xAxis={[\n            {\n              scaleType: \"linear\",\n              min: xAxisStats.min,\n              max: xAxisStats.max,\n              label: DIAMETER,\n              height: 60,\n              labelStyle: { fontSize: 16, fill: t.ink },\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            },\n          ]}\n          yAxis={[\n            {\n              scaleType: \"linear\",\n              min: yAxisStats.min,\n              max: yAxisStats.max,\n              label: WEIGHT,\n              width: 72,\n              labelStyle: { fontSize: 16, fill: t.ink },\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            },\n          ]}\n          sx={{\n            \"& .MuiScatterChart-marker\": { fillOpacity: 0.3 },\n            \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n            \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n            \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          }}\n        >\n          <ContourLines />\n        </ScatterChart>\n        <Box sx={{ width: LEGEND_W, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", gap: \"10px\", pl: \"12px\" }}>\n          <Typography sx={{ fontSize: 15, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>Density contours</Typography>\n          {[...contours].reverse().map((c) => (\n            <Box key={c.fraction} sx={{ display: \"flex\", alignItems: \"center\", gap: \"10px\" }}>\n              <Box sx={{ width: 26, height: `${c.strokeWidth}px`, borderRadius: \"3px\", bgcolor: c.color, flexShrink: 0 }} />\n              <Typography sx={{ fontSize: 14, color: t.inkSoft }}>{`${Math.round(c.fraction * 100)} % of peak`}</Typography>\n            </Box>\n          ))}\n        </Box>\n      </Box>\n    </Box>\n  );\n}\n"}