{"spec_id":"scatter-regression-polynomial","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-regression-polynomial: Scatter Plot with Polynomial Regression\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst POLY_DEGREE = 2; // quadratic by default; 3 or 4 only when the pattern calls for it\nconst DEGREE_NAMES: Record<number, string> = { 2: \"Quadratic\", 3: \"Cubic\", 4: \"Quartic\" };\nconst SUPERSCRIPTS = [\"\", \"\", \"²\", \"³\", \"⁴\"];\nconst CURVE_POINTS = 60; // x positions at which the fitted polynomial is evaluated\nconst POINT_OPACITY = 0.67;\nconst X_PAD_SHARE = 0.03; // axis padding as a share of the data span\nconst Y_PAD_SHARE = 0.08;\n\n// Columns: set these to your data's column names\nconst X = \"Horizontal distance (m)\"; // role: x\nconst Y = \"Height (m)\"; // role: y\n\n// Data: replace this block with your own records, one object per row\n// Tracked ball flight: h(x) = -g / (2 v0x²) x² + (v0y / v0x) x + h0, plus sensor noise.\nconst V0X = 18; // horizontal release velocity, m/s\nconst V0Y = 14; // vertical release velocity, m/s\nconst H0 = 1.3; // release height, m\nconst G = 9.81; // m/s²\nconst trueA = -G / (2 * V0X ** 2);\nconst trueB = V0Y / V0X;\nconst flightRange = (-trueB - Math.sqrt(trueB ** 2 - 4 * trueA * H0)) / (2 * trueA);\nconst data: Record<string, number>[] = [];\nlet seed = 42;\nfor (let i = 0; i < 85; i += 1) {\n  seed = (seed * 1664525 + 1013904223) % 4294967296;\n  const x = (seed / 4294967296) * flightRange;\n  seed = (seed * 1664525 + 1013904223) % 4294967296;\n  const u1 = Math.max(seed / 4294967296, 1e-9);\n  seed = (seed * 1664525 + 1013904223) % 4294967296;\n  const u2 = seed / 4294967296;\n  const noise = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n  const measured = Math.max(trueA * x ** 2 + trueB * x + H0 + noise * 0.4, 0);\n  data.push({ [X]: Number(x.toFixed(2)), [Y]: Number(measured.toFixed(2)) });\n}\n\n// Plot: reads only data and the constants above\nconst xs = data.map((d) => d[X]);\nconst ys = data.map((d) => d[Y]);\nconst n = data.length;\n\n// Least squares: normal equations (AᵀA)c = Aᵀy, solved by Gauss-Jordan with partial pivoting\nconst size = POLY_DEGREE + 1;\nconst augmented: number[][] = Array.from({ length: size }, () => new Array(size + 1).fill(0));\nfor (let i = 0; i < n; i += 1) {\n  for (let r = 0; r < size; r += 1) {\n    augmented[r][size] += xs[i] ** r * ys[i];\n    for (let c = 0; c < size; c += 1) augmented[r][c] += xs[i] ** (r + c);\n  }\n}\nfor (let col = 0; col < size; col += 1) {\n  let pivotRow = col;\n  for (let row = col + 1; row < size; row += 1) {\n    if (Math.abs(augmented[row][col]) > Math.abs(augmented[pivotRow][col])) pivotRow = row;\n  }\n  [augmented[col], augmented[pivotRow]] = [augmented[pivotRow], augmented[col]];\n  const pivot = augmented[col][col];\n  for (let c = col; c <= size; c += 1) augmented[col][c] /= pivot;\n  for (let row = 0; row < size; row += 1) {\n    if (row === col) continue;\n    const factor = augmented[row][col];\n    for (let c = col; c <= size; c += 1) augmented[row][c] -= factor * augmented[col][c];\n  }\n}\nconst coeffs = augmented.map((row) => row[size]); // ascending powers: c0, c1, c2, ...\n\nconst fitted = xs.map((x) => coeffs.reduce((sum, c, k) => sum + c * x ** k, 0));\nconst yMean = ys.reduce((sum, y) => sum + y, 0) / n;\nconst ssRes = ys.reduce((sum, y, i) => sum + (y - fitted[i]) ** 2, 0);\nconst ssTot = ys.reduce((sum, y) => sum + (y - yMean) ** 2, 0);\nconst rSquared = 1 - ssRes / ssTot;\n\nconst xMin = Math.min(...xs);\nconst xMax = Math.max(...xs);\nconst curveX = Array.from({ length: CURVE_POINTS }, (_, i) => xMin + ((xMax - xMin) * i) / (CURVE_POINTS - 1));\nconst curveY = curveX.map((x) => coeffs.reduce((sum, c, k) => sum + c * x ** k, 0));\n\nconst xPad = (xMax - xMin) * X_PAD_SHARE;\nconst yLow = Math.min(...ys, ...curveY);\nconst yHigh = Math.max(...ys, ...curveY);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\nconst equation = `y = ${coeffs\n  .map((c, k) => ({ c, k }))\n  .reverse()\n  .map(({ c, k }, i) => {\n    const sign = c < 0 ? \"−\" : i === 0 ? \"\" : \"+\";\n    const term = `${Math.abs(c).toPrecision(3)}${k > 0 ? \"x\" : \"\"}${SUPERSCRIPTS[k]}`;\n    return i === 0 ? `${sign}${term}` : `${sign} ${term}`;\n  })\n  .join(\" \")}`;\nconst fitName = DEGREE_NAMES[POLY_DEGREE];\n\nconst scatterData = data.map((d, i) => ({ x: d[X], y: d[Y], id: i }));\nconst title = \"Polynomial Regression · scatter-regression-polynomial · javascript · muix · anyplot.ai\";\nconst HEADER_H = 112;\nconst LEGEND_H = 40;\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\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n          alignItems: \"center\",\n          gap: 8,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{title}</div>\n        <div style={{ display: \"flex\", alignItems: \"baseline\", gap: 24 }}>\n          <span style={{ fontSize: 24, fontWeight: 700, color: t.ink }}>R² = {rSquared.toFixed(3)}</span>\n          <span style={{ fontSize: 16, color: t.inkSoft }}>\n            {fitName} least-squares fit: {equation} · n = {n}\n          </span>\n        </div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        margin={{ top: 12, right: 56, bottom: 16, left: 32 }}\n        skipAnimation\n        series={[\n          {\n            type: \"scatter\",\n            id: \"observations\",\n            label: \"Observations\",\n            data: scatterData,\n            markerSize: 7,\n            color: t.palette[0],\n          },\n          {\n            type: \"line\",\n            id: \"fit\",\n            label: `${fitName} fit (degree ${POLY_DEGREE})`,\n            data: curveY,\n            curve: \"natural\",\n            color: t.palette[1],\n            showMark: false,\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            data: curveX,\n            min: xMin - xPad,\n            max: xMax + xPad,\n            label: X,\n            height: 68,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n            sx: { \"& .MuiChartsAxis-line, & .MuiChartsAxis-tick\": { stroke: t.inkSoft } },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yLow - yPad,\n            max: yHigh + yPad,\n            label: Y,\n            width: 72,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n            sx: { \"& .MuiChartsAxis-line, & .MuiChartsAxis-tick\": { stroke: t.inkSoft } },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ horizontal: \"end\", vertical: \"top\" }} legendDirection=\"horizontal\">\n          <ChartsLegend\n            sx={{\n              fontSize: 16,\n              color: t.ink,\n              pr: 7,\n              '& [data-series=\"observations\"] .MuiChartsLegend-mark': { opacity: POINT_OPACITY },\n            }}\n          />\n          <ChartsSurface\n            sx={{\n              \"& .MuiScatterChart-marker\": { fillOpacity: POINT_OPACITY },\n              \"& .MuiLineChart-line\": { strokeWidth: 3.5 },\n            }}\n          >\n            <ChartsGrid horizontal vertical />\n            <ScatterPlot />\n            <LinePlot skipAnimation />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"item\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}