lin_data = {
const r = rng(707 + lin_seed);
const n = 80;
const x = runif(r, n, 0, 4);
const e = rnorm(r, n, 0, 1);
let y;
if (lin_type === "up") y = x.map((v, i) => 1 + 1.5 * v + e[i]);
if (lin_type === "down") y = x.map((v, i) => 8 - 1.5 * v + e[i]);
if (lin_type === "curve") y = x.map((v, i) => 1 + 0.6 * v ** 3 + 2 * e[i]);
if (lin_type === "fan") y = x.map((v, i) => 2 + 1.2 * v + e[i] * (0.2 + 1.1 * v));
if (lin_type === "outlier") { y = x.map((v, i) => 2 + 0.3 * v + 0.8 * e[i]); x[0] = 3.9; y[0] = 14; }
const fit = lm1(x, y);
const pts = x.map((v, i) => ({x: v, y: y[i], fitted: fit.fitted[i], resid: fit.resid[i], std: fit.stdres[i]}));
return {pts, fit};
}
lin_scatter = Plot.plot({
width: 560, height: 250, marginLeft: 45,
x: {label: "x (predictor)"}, y: {label: "y (response)", grid: true},
marks: [
lin_resid ? Plot.link(lin_data.pts, {x1: "x", x2: "x", y1: "y", y2: "fitted", stroke: red, strokeOpacity: 0.5}) : null,
Plot.dot(lin_data.pts, {x: "x", y: "y", fill: grey, r: 3}),
Plot.line(lin_data.pts.slice().sort((a, b) => a.x - b.x), {x: "x", y: "fitted", stroke: red, strokeWidth: 2.5})
]
})
lin_resplot = Plot.plot({
width: 275, height: 210, marginLeft: 45,
x: {label: "Fitted values"}, y: {label: "Residuals", grid: true},
marks: [
Plot.ruleY([0], {stroke: dark, strokeDasharray: "4,3"}),
Plot.dot(lin_data.pts, {x: "fitted", y: "resid", fill: grey, r: 2.5}),
Plot.line(smooth(lin_data.pts.map((d) => d.fitted), lin_data.pts.map((d) => d.resid)), {x: "x", y: "y", stroke: red, strokeWidth: 2})
]
})
lin_qq = Plot.plot({
width: 275, height: 210, marginLeft: 45,
x: {label: "Theoretical quantiles"}, y: {label: "Standardised residuals", grid: true},
marks: [
Plot.line([[-2.6, -2.6], [2.6, 2.6]], {stroke: red, strokeWidth: 2}),
Plot.dot(qqpoints(lin_data.pts.map((d) => d.std)), {x: "theoretical", y: "sample", fill: grey, r: 2.5})
]
})
html`<div>${lin_scatter}<div class="app-row"><div><div class="app-plot-label">Residuals vs fitted</div>${lin_resplot}</div><div><div class="app-plot-label">Normal Q-Q plot of residuals</div>${lin_qq}</div></div>
<div class="app-verdict">R<sup>2</sup> = <b>${fmt(lin_data.fit.r2)}</b>, slope = <b>${fmt(lin_data.fit.b1)}</b>, <i>p</i> ${fmtp(lin_data.fit.p)}.
${{up: "A good fit: residuals are a flat cloud and the Q-Q points sit on the line.",
down: "A good fit: the direction of the slope does not matter, only the pattern of the residuals.",
curve: "A poor fit: the residuals form a U-shape. The relationship is curved, so a straight line is the wrong model.",
fan: "A poor fit: the residuals spread out as fitted values increase (unequal variance). A log transformation or a GLM may help.",
outlier: "One point drags the line and creates a long tail in the Q-Q plot. Check whether it is a data entry error."}[lin_type]}</div></div>`