{"spec_id":"residual-plot","library":"muix","language":"javascript","code":"// anyplot.ai\n// residual-plot: Residual Plot\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { ScatterChart } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst OUTLIER_SD = 2; // residuals beyond this many standard deviations count as outliers\nconst OUTLIER_COLOR = t.palette[4]; // alert red for the outliers; the bulk keeps the brand green\nconst PAD_SHARE = 0.04; // axis padding beyond the outermost points and bands, share of the span\nconst TITLE_H = 48;\nconst SUBTITLE_H = 28;\nconst LEGEND_H = 44;\n\n// Columns: set these to your data's column names\nconst OBSERVED = \"Observed price (USD)\"; // role: y_true\nconst PREDICTED = \"Predicted price (USD)\"; // role: y_pred\n\n// Data: replace this block with your own records, one object per row\n// 220 home sales: price regressed on floor area (600–3500 sq ft) by ordinary least squares, with\n// noise that widens for larger homes; fixed-seed LCG with Box-Muller normals\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    return seed / 0x7fffffff;\n  };\n  const sqft = Array.from({ length: 220 }, () => 600 + rand() * 2900);\n  const price = sqft.map((s) => {\n    const z = Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n    return 42000 + s * 118 + z * (8000 + s * 18);\n  });\n  const mx = sqft.reduce((a, b) => a + b, 0) / sqft.length;\n  const my = price.reduce((a, b) => a + b, 0) / price.length;\n  const slope =\n    sqft.reduce((a, s, i) => a + (s - mx) * (price[i] - my), 0) / sqft.reduce((a, s) => a + (s - mx) ** 2, 0);\n  return sqft.map((s, i) => ({\n    [OBSERVED]: Math.round(price[i]),\n    [PREDICTED]: Math.round(my + slope * (s - mx)),\n  }));\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => Number.isFinite(d[OBSERVED]) && Number.isFinite(d[PREDICTED]));\nconst points = rows.map((d, i) => ({ x: d[PREDICTED], y: d[OBSERVED] - d[PREDICTED], id: i }));\nconst meanResidual = points.reduce((s, p) => s + p.y, 0) / points.length;\nconst sd = Math.sqrt(points.reduce((s, p) => s + (p.y - meanResidual) ** 2, 0) / (points.length - 1));\nconst limit = OUTLIER_SD * sd;\nconst inliers = points.filter((p) => Math.abs(p.y) <= limit);\nconst outliers = points.filter((p) => Math.abs(p.y) > limit);\nconst xs = points.map((p) => p.x);\nconst ys = [...points.map((p) => p.y), limit, -limit];\nconst xPad = (Math.max(...xs) - Math.min(...xs)) * PAD_SHARE;\nconst yPad = (Math.max(...ys) - Math.min(...ys)) * PAD_SHARE;\n\nconst unit = OBSERVED.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst fmt = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 0 });\nconst TITLE = \"residual-plot · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${points.length} observations · residual = observed − predicted · SD ${fmt.format(sd)} ${unit} · ${outliers.length} beyond ±${OUTLIER_SD}σ`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, display: \"flex\", alignItems: \"flex-end\", justifyContent: \"center\", fontSize: 22, fontWeight: 600, color: t.ink }}>\n        {TITLE}\n      </div>\n      <div style={{ height: SUBTITLE_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", fontSize: 15, color: t.inkSoft }}>\n        {SUBTITLE}\n      </div>\n      <ScatterChart\n        width={width}\n        height={height - TITLE_H - SUBTITLE_H - LEGEND_H}\n        skipAnimation\n        margin={{ top: 12, right: 40, bottom: 8, left: 16 }}\n        grid={{ horizontal: true, vertical: true }}\n        series={[\n          { id: \"residuals\", data: inliers, label: `Residuals within ±${OUTLIER_SD}σ`, markerSize: 6, color: t.palette[0] },\n          { id: \"outliers\", data: outliers, label: `Outliers beyond ±${OUTLIER_SD}σ`, markerSize: 8, color: OUTLIER_COLOR },\n        ]}\n        xAxis={[\n          {\n            label: PREDICTED,\n            min: Math.min(...xs) - xPad,\n            max: Math.max(...xs) + xPad,\n            tickNumber: 9,\n            height: 64,\n            valueFormatter: (v) => fmt.format(v),\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            label: `Residual (${unit})`,\n            min: Math.min(...ys) - yPad,\n            max: Math.max(...ys) + yPad,\n            width: 92,\n            valueFormatter: (v) => fmt.format(v),\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiScatterChart-marker\": { stroke: t.pageBg, strokeWidth: 1 },\n          '& [data-series=\"residuals\"] .MuiScatterChart-marker': { fillOpacity: 0.6 },\n        }}\n      >\n        <ChartsReferenceLine\n          y={0}\n          label=\"Perfect prediction: residual = 0\"\n          labelAlign=\"end\"\n          spacing={{ x: 8, y: 8 }}\n          lineStyle={{ stroke: t.ink, strokeWidth: 2 }}\n          labelStyle={{ fill: t.ink, fontSize: 14, fontWeight: 600, stroke: t.pageBg, strokeWidth: 4, paintOrder: \"stroke\" }}\n        />\n        {[1, -1].map((side) => (\n          <ChartsReferenceLine\n            key={side}\n            y={side * limit}\n            label={`${side > 0 ? \"+\" : \"−\"}${OUTLIER_SD}σ = ${side > 0 ? \"\" : \"−\"}${fmt.format(limit)}`}\n            labelAlign=\"end\"\n            spacing={{ x: 8, y: 8 }}\n            lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"8 6\", strokeWidth: 1.5 }}\n            labelStyle={{ fill: t.inkSoft, fontSize: 14, stroke: t.pageBg, strokeWidth: 4, paintOrder: \"stroke\" }}\n          />\n        ))}\n      </ScatterChart>\n    </div>\n  );\n}\n"}