{"spec_id":"scatter-regression-linear","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-regression-linear: Scatter Plot with Linear Regression\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n// The muted anchor (confidence-band fill), theme-adaptive like the chrome\nconst MUTED = window.ANYPLOT_THEME === \"dark\" ? \"#A8A79F\" : \"#6B6A63\";\n\n// Constants\nconst CONFIDENCE_LEVEL = 95; // two-sided confidence band for the mean response, percent\n// Two-tailed t critical values by level (percent): [degrees of freedom, t]. The band takes the\n// entry with the largest df not above the fit's own, so it is never narrower than exact; a level\n// without a table fails loudly instead of mislabelling the band.\nconst T_CRIT = {\n  95: [\n    [1, 12.706], [2, 4.303], [3, 3.182], [4, 2.776], [5, 2.571], [6, 2.447], [7, 2.365], [8, 2.306],\n    [9, 2.262], [10, 2.228], [12, 2.179], [15, 2.131], [20, 2.086], [25, 2.06], [30, 2.042],\n    [40, 2.021], [60, 2.0], [80, 1.99], [100, 1.984], [120, 1.98], [1000, 1.962],\n  ],\n};\nconst GRID_POINTS = 60; // samples along the fitted line and its band\nconst X_PAD_SHARE = 0.04; // room beyond the outermost observations, as a share of the x span\nconst Y_PAD_SHARE = 0.08;\nconst POINT_OPACITY = 0.65;\nconst NOTE_INSET = 28; // px from the plot corner to the fit statistics\n\n// Columns: set these to your data's column names\nconst AD_SPEND = \"Advertising spend ($k)\"; // role: x\nconst REVENUE = \"Sales revenue ($k)\"; // role: y\n\n// Data: replace this block with your own records, one object per row\n// 90 regional campaigns: advertising spend against sales revenue, linear with noise.\nconst data = (() => {\n  let state = 42;\n  const uniform = () => {\n    state = (state * 1664525 + 1013904223) % 4294967296;\n    return state / 4294967296;\n  };\n  return Array.from({ length: 90 }, () => {\n    const spend = 5 + uniform() * 45;\n    const noise = Math.sqrt(-2 * Math.log(Math.max(uniform(), 1e-9))) * Math.cos(2 * Math.PI * uniform());\n    const revenue = 22 + spend * 3.4 + noise * 24;\n    return { [AD_SPEND]: Number(spend.toFixed(2)), [REVENUE]: Number(Math.max(revenue, 8).toFixed(2)) };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst xs = data.map((d) => d[AD_SPEND]);\nconst ys = data.map((d) => d[REVENUE]);\nconst n = data.length;\nconst xMean = xs.reduce((a, b) => a + b, 0) / n;\nconst yMean = ys.reduce((a, b) => a + b, 0) / n;\nconst sxy = data.reduce((s, d) => s + (d[AD_SPEND] - xMean) * (d[REVENUE] - yMean), 0);\nconst sxx = xs.reduce((s, x) => s + (x - xMean) ** 2, 0);\nconst slope = sxy / sxx;\nconst intercept = yMean - slope * xMean;\nconst ssRes = data.reduce((s, d) => s + (d[REVENUE] - (intercept + slope * d[AD_SPEND])) ** 2, 0);\nconst ssTot = ys.reduce((s, y) => s + (y - yMean) ** 2, 0);\nconst rSquared = 1 - ssRes / ssTot;\nconst correlation = Math.sign(slope) * Math.sqrt(rSquared);\nconst df = n - 2;\nconst residualStdErr = Math.sqrt(ssRes / df);\nconst tCrit = T_CRIT[CONFIDENCE_LEVEL].filter(([d]) => d <= df).pop()[1];\n\nconst xMin = Math.min(...xs);\nconst xMax = Math.max(...xs);\nconst gridX = Array.from({ length: GRID_POINTS }, (_, i) => xMin + ((xMax - xMin) * i) / (GRID_POINTS - 1));\nconst fittedY = gridX.map((x) => intercept + slope * x);\nconst halfWidth = gridX.map((x) => tCrit * residualStdErr * Math.sqrt(1 / n + (x - xMean) ** 2 / sxx));\nconst upperY = fittedY.map((y, i) => y + halfWidth[i]);\nconst lowerY = fittedY.map((y, i) => y - halfWidth[i]);\n\nconst xPad = (xMax - xMin) * X_PAD_SHARE;\nconst yAll = [...ys, ...upperY, ...lowerY];\nconst yPad = (Math.max(...yAll) - Math.min(...yAll)) * Y_PAD_SHARE;\n\nconst TITLE = \"scatter-regression-linear · javascript · muix · anyplot.ai\";\nconst STATS = `Least-squares fit to n = ${n} observations   ·   r = ${correlation.toFixed(3).replace(\"-\", \"−\")}`;\nconst BAND_NOTE = `Shaded band: ${CONFIDENCE_LEVEL}% confidence interval for the mean response`;\nconst R_SQUARED_NOTE = `R² = ${rSquared.toFixed(3)}`;\nconst EQUATION_NOTE = `y = ${slope.toFixed(2).replace(\"-\", \"−\")}x ${intercept < 0 ? \"−\" : \"+\"} ${Math.abs(intercept).toFixed(1)}`;\nconst HEADER_HEIGHT = 104;\n\nfunction ConfidenceBand() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const upper = gridX.map((x, i) => `${xScale(x)},${yScale(upperY[i])}`).join(\" L \");\n  const lower = [...gridX.keys()].reverse().map((i) => `${xScale(gridX[i])},${yScale(lowerY[i])}`).join(\" L \");\n  return <path d={`M ${upper} L ${lower} Z`} fill={MUTED} fillOpacity={0.24} stroke=\"none\" />;\n}\n\n// The fit statistics go into the top corner the line leaves empty: top left for a rising fit,\n// top right for a falling one\nfunction FitNote() {\n  const { left, top, width } = useDrawingArea();\n  const rising = slope >= 0;\n  const x = rising ? left + NOTE_INSET : left + width - NOTE_INSET;\n  const anchor = rising ? \"start\" : \"end\";\n  return (\n    <g>\n      <text x={x} y={top + NOTE_INSET + 18} textAnchor={anchor} fontSize={22} fontWeight={600} fill={t.ink}>\n        {R_SQUARED_NOTE}\n      </text>\n      <text x={x} y={top + NOTE_INSET + 44} textAnchor={anchor} fontSize={16} fill={t.inkSoft}>\n        {EQUATION_NOTE}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 16, color: t.ink }}>{STATS}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{BAND_NOTE}</div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_HEIGHT}\n        margin={{ top: 8, right: 48, bottom: 12, left: 32 }}\n        skipAnimation\n        series={[\n          {\n            type: \"scatter\",\n            id: \"observations\",\n            label: \"Observations\",\n            data: data.map((d, i) => ({ id: `pt-${i}`, x: d[AD_SPEND], y: d[REVENUE] })),\n            markerSize: 7,\n            color: t.palette[0],\n          },\n          {\n            type: \"line\",\n            id: \"fit\",\n            label: \"Least-squares fit\",\n            data: fittedY,\n            curve: \"linear\",\n            color: t.ink,\n            showMark: false,\n            disableHighlight: true,\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"x\",\n            data: gridX,\n            scaleType: \"linear\",\n            min: xMin - xPad,\n            max: xMax + xPad,\n            label: AD_SPEND,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 17, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"y\",\n            scaleType: \"linear\",\n            min: Math.min(...yAll) - yPad,\n            max: Math.max(...yAll) + yPad,\n            label: REVENUE,\n            width: 80,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 17, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper hideLegend>\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiScatterChart-marker\": { fillOpacity: POINT_OPACITY, stroke: t.pageBg, strokeWidth: 1 },\n              \"& .MuiLineChart-line\": { strokeWidth: 3 },\n            }}\n          >\n            <ChartsGrid horizontal vertical />\n            <ConfidenceBand />\n            <ScatterPlot />\n            <LinePlot skipAnimation />\n            <FitNote />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}