Prompt specification
Build or customize the Three.js 3D scene "Regression sensitivity exploration board" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Regression sensitivity exploration board
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/regression-sensitivity-exploration-board-x1788
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts correlation and regression in paired observations. Let users move points or add an outlier and watch the fitted line change; display residuals and explain the limits of extrapolating beyond observed values. Low-poly.
Working Three.js Starter (regression-sensitivity-exploration-board-x1788):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Correlation & Regression Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: #0d1825;
--panel-2: #111f2f;
--line: #24364a;
--text: #edf5ff;
--muted: #91a4b8;
--mint: #5de4c4;
--amber: #ffb55b;
--coral: #ff7377;
--blue: #72a9ff;
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
button,
input {
font: inherit;
}
button:focus-visible,
canvas:focus-visible,
input:focus-visible {
outline: 2px solid var(--mint);
outline-offset: 3px;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 360px;
width: 100%;
height: 100dvh;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 42% 35%, #17283c 0, #0a1522 45%, #07111d 100%);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-header {
position: absolute;
top: 22px;
left: 24px;
z-index: 2;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--mint);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 13px var(--mint);
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 34px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
max-width: 540px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.legend {
position: absolute;
left: 22px;
bottom: 24px;
z-index: 2;
display: grid;
gap: 8px;
padding: 12px 14px;
border: 1px solid rgba(157, 184, 211, 0.16);
border-radius: 12px;
background: rgba(7, 17, 29, 0.78);
backdrop-filter: blur(10px);
pointer-events: none;
font-size: 11px;
color: #bfcede;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.legend-mark {
width: 18px;
height: 4px;
border-radius: 4px;
background: var(--mint);
}
.legend-mark.dashed {
height: 0;
border-top: 3px dashed var(--amber);
background: transparent;
}
.legend-mark.diamond {
width: 10px;
height: 10px;
margin: 0 4px;
transform: rotate(45deg);
background: #f4f8fc;
}
.legend-mark.residual {
background: linear-gradient(90deg, var(--coral) 50%, var(--blue) 50%);
}
.view-hint {
position: absolute;
right: 18px;
bottom: 22px;
z-index: 2;
max-width: 290px;
padding: 9px 12px;
border: 1px solid rgba(157, 184, 211, 0.13);
border-radius: 10px;
background: rgba(7, 17, 29, 0.7);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
text-align: right;
pointer-events: none;
}
#tooltip {
position: absolute;
z-index: 8;
display: none;
min-width: 190px;
padding: 11px 12px;
border: 1px solid rgba(93, 228, 196, 0.35);
border-radius: 10px;
background: rgba(5, 13, 23, 0.94);
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.28);
pointer-events: none;
font-size: 12px;
line-height: 1.55;
}
#tooltip strong {
display: block;
margin-bottom: 3px;
color: var(--mint);
font-size: 12px;
}
.tooltip-grid {
display: grid;
grid-template-columns: auto auto;
gap: 1px 14px;
color: var(--muted);
}
.tooltip-grid b {
color: var(--text);
font-weight: 650;
text-align: right;
}
#panel {
min-height: 0;
overflow-y: auto;
padding: 22px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.018), transparent 160px),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #30465d transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 18px;
}
.panel-heading h2 {
margin: 0;
font-size: 18px;
letter-spacing: -0.02em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
#statusChip {
flex: 0 0 auto;
padding: 5px 8px;
border: 1px solid rgba(93, 228, 196, 0.25);
border-radius: 999px;
background: rgba(93, 228, 196, 0.08);
color: var(--mint);
font-size: 10px;
font-weight: 750;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.card {
margin-bottom: 14px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(17, 31, 47, 0.68);
}
.section-label {
margin-bottom: 11px;
color: #aebfd0;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 9px;
}
.metric {
padding: 11px;
border: 1px solid rgba(129, 154, 181, 0.12);
border-radius: 10px;
background: rgba(4, 12, 21, 0.28);
}
.metric-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.metric-value {
font-size: 22px;
font-weight: 760;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.meter {
height: 5px;
margin-top: 12px;
overflow: hidden;
border-radius: 999px;
background: #263648;
}
#rMeterFill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--mint);
transition: width 100ms ease-out, background 100ms ease-out;
}
.equation {
margin-top: 14px;
padding: 11px 12px;
border-left: 3px solid var(--mint);
border-radius: 0 8px 8px 0;
background: rgba(93, 228, 196, 0.055);
color: #d9fff5;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
}
#modelNote {
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 39px;
padding: 9px 11px;
border: 1px solid #30445a;
border-radius: 9px;
background: #142538;
color: var(--text);
cursor: pointer;
font-size: 12px;
font-weight: 650;
transition:
transform 100ms ease,
border-color 100ms ease,
background 100ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: #526d87;
background: #193047;
}
button:active {
transform: translateY(0);
}
button.primary {
grid-column: 1 / -1;
border-color: rgba(93, 228, 196, 0.5);
background: rgba(93, 228, 196, 0.13);
color: #baffed;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 12px;
color: #c7d5e3;
font-size: 12px;
}
.toggle-row input {
width: 17px;
height: 17px;
accent-color: var(--mint);
}
.residual-summary {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 10px;
}
.residual-summary > div {
padding: 9px;
border-radius: 8px;
background: rgba(4, 12, 21, 0.35);
}
.residual-summary span {
display: block;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
}
.residual-summary strong {
display: block;
margin-top: 2px;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
details summary {
cursor: pointer;
color: #b8c7d6;
font-size: 11px;
}
#residualList {
display: grid;
gap: 4px;
max-height: 142px;
margin-top: 9px;
overflow-y: auto;
}
.res-row {
display: flex;
justify-content: space-between;
padding: 5px 7px;
border-radius: 6px;
background: rgba(4, 12, 21, 0.3);
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.res-row b.positive {
color: var(--coral);
}
.res-row b.negative {
color: var(--blue);
}
.res-row b.near-zero {
color: var(--mint);
}
.explanation {
border-color: rgba(255, 181, 91, 0.25);
background: rgba(255, 181, 91, 0.055);
}
.explanation .section-label {
color: var(--amber);
}
#extrapolationText,
#causationText {
margin: 0 0 10px;
color: #c2cfda;
font-size: 12px;
line-height: 1.55;
}
#causationText {
margin-bottom: 0;
}
.support {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid rgba(255, 181, 91, 0.15);
color: var(--muted);
font-size: 11px;
}
.support strong {
color: var(--text);
}
@media (max-width: 860px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: minmax(320px, 58%) minmax(0, 42%);
}
#panel {
padding: 16px;
border-top: 1px solid var(--line);
border-left: 0;
}
.scene-header {
top: 14px;
left: 16px;
}
.subtitle {
max-width: 330px;
font-size: 11px;
}
.legend {
left: 12px;
bottom: 12px;
padding: 9px 10px;
}
.view-hint {
right: 10px;
bottom: 10px;
max-width: 180px;
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="app">
<main id="stage" aria-label="Interactive correlation and regression visualization">
<canvas
id="scene"
tabindex="0"
aria-label="Paired observations chart. Drag a diamond to move an observation. Drag empty space to orbit the camera."
></canvas>
<header class="scene-header">
<div class="eyebrow"><span class="live-dot"></span>Live model</div>
<h1>Correlation & Regression Lab</h1>
<p class="subtitle">
Move an observation or add an influential point. The least-squares line,
residuals, and statistics update immediately.
</p>
</header>
<div class="legend" aria-hidden="true">
<div class="legend-row"><span class="legend-mark diamond"></span>Paired observation</div>
<div class="legend-row"><span class="legend-mark"></span>Fitted line within observed support</div>
<div class="legend-row"><span class="legend-mark dashed"></span>Extrapolated segment</div>
<div class="legend-row"><span class="legend-mark residual"></span>Residual: observed − fitted</div>
</div>
<div class="view-hint">
Drag diamonds to move data · drag empty space to orbit · wheel to zoom
</div>
<div id="tooltip" role="status" aria-live="polite"></div>
</main>
<aside id="panel">
<div class="panel-heading">
<div>
<h2>Model readout</h2>
<p>Ordinary least squares with an intercept</p>
</div>
<span id="statusChip">Positive</span>
</div>
<section class="card" aria-label="Regression statistics">
<div class="section-label">Live statistics</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Pearson r</span>
<strong class="metric-value" id="rValue">0.00</strong>
</div>
<div class="metric">
<span class="metric-label">R²</span>
<strong class="metric-value" id="r2Value">0.00</strong>
</div>
<div class="metric">
<span class="metric-label">Slope</span>
<strong class="metric-value" id="slopeValue">0.00</strong>
</div>
<div class="metric">
<span class="metric-label">Observations</span>
<strong class="metric-value" id="nValue">0</strong>
</div>
</div>
<div class="meter" aria-hidden="true"><div id="rMeterFill"></div></div>
<div class="equation" id="equation">ŷ = 0.00 + 0.00x</div>
<p id="modelNote"></p>
</section>
<section class="card" aria-label="Interaction controls">
<div class="section-label">Experiment</div>
<div class="button-row">
<button class="primary" id="addOutlier">+ Add influential point</button>
<button id="resetData">Reset data</button>
<button id="resetView">Reset camera</button>
</div>
<label class="toggle-row">
<span>Show residual sticks</span>
<input id="toggleResiduals" type="checkbox" checked>
</label>
</section>
<section class="card" aria-label="Residual statistics">
<div class="section-label">Residuals</div>
<div class="residual-summary">
<div><span>Mean absolute</span><strong id="maeValue">0.00</strong></div>
<div><span>RMSE</span><strong id="rmseValue">0.00</strong></div>
</div>
<details>
<summary>Show residual values</summary>
<div id="residualList"></div>
</details>
</section>
<section class="card explanation" aria-label="Extrapolation warning">
<div class="section-label">Limits of the model</div>
<p id="extrapolationText"></p>
<div class="support">
<span>Observed x range</span>
<strong id="supportValue">—</strong>
</div>
<p id="causationText"></p>
</section>
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// DOM and application state
// ------------------------------------------------------------
const stage = document.querySelector("#stage");
const canvas = document.querySelector("#scene");
const tooltip = document.querySelector("#tooltip");
const ui = {
rValue: document.querySelector("#rValue"),
r2Value: document.querySelector("#r2Value"),
slopeValue: document.querySelector("#slopeValue"),
nValue: document.querySelector("#nValue"),
rMeterFill: document.querySelector("#rMeterFill"),
equation: document.querySelector("#equation"),
modelNote: document.querySelector("#modelNote"),
statusChip: document.querySelector("#statusChip"),
maeValue: document.querySelector("#maeValue"),
rmseValue: document.querySelector("#rmseValue"),
residualList: document.querySelector("#residualList"),
extrapolationText: document.querySelector("#extrapolationText"),
supportValue: document.querySelector("#supportValue"),
causationText: document.querySelector("#causationText"),
addOutlier: document.querySelector("#addOutlier"),
resetData: document.querySelector("#resetData"),
resetView: document.querySelector("#resetView"),
toggleResiduals: document.querySelector("#toggleResiduals")
};
const initialData = [
{ x: 1.1, y: 2.2 },
{ x: 2.0, y: 3.8 },
{ x: 3.1, y: 3.4 },
{ x: 4.0, y: 5.4 },
{ x: 5.0, y: 6.5 },
{ x: 6.1, y: 5.9 },
{ x: 7.0, y: 7.7 },
{ x: 8.1, y: 8.3 },
{ x: 9.0, y: 9.4 }
];
let data = initialData.map((d) => ({ ...d }));
let nextId = initialData.length + 1;
let selectedId = null;
let hoveredPoint = null;
let model = null;
const bounds = {
minX: 0,
maxX: 10,
minY: 0,
maxY: 12,
pointZ: 0.38
};
const colors = {
mint: 0x5de4c4,
amber: 0xffb55b,
coral: 0xff7377,
blue: 0x72a9ff,
point: 0xf4f8fc,
grid: 0x4b6278
};
// ------------------------------------------------------------
// Three.js setup
// ------------------------------------------------------------
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
42,
stage.clientWidth / stage.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
scene.add(new THREE.AmbientLight(0xb9d8f2, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(6, 12, 12);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x65d8c5, 1.5);
rimLight.position.set(-8, 2, 7);
scene.add(rimLight);
const pointGroup = new THREE.Group();
const residualGroup = new THREE.Group();
scene.add(pointGroup, residualGroup);
const unitBoxGeometry = new THREE.BoxGeometry(1, 1, 1);
const markerGeometry = new THREE.OctahedronGeometry(0.23, 0);
const shadowGeometry = new THREE.CircleGeometry(0.13, 12);
const residualCapGeometry = new THREE.BoxGeometry(0.10, 0.10, 0.10);
const shadowMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.26,
depthWrite: false
});
const stemMaterial = new THREE.LineBasicMaterial({
color: 0x9db1c5,
transparent: true,
opacity: 0.42
});
const pointVisuals = new Map();
const markerMeshes = [];
// ------------------------------------------------------------
// Static chart, axes, grid, labels
// ------------------------------------------------------------
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(10.65, 12.65),
new THREE.MeshStandardMaterial({
color: 0x0d1928,
roughness: 0.95,
metalness: 0,
side: THREE.DoubleSide
})
);
backdrop.position.set(5, 6, -0.24);
scene.add(backdrop);
const gridPositions = [];
for (let x = 0; x <= 10; x += 1) {
gridPositions.push(x, 0, -0.08, x, 12, -0.08);
}
for (let y = 0; y <= 12; y += 1) {
gridPositions.push(0, y, -0.08, 10, y, -0.08);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: colors.grid,
transparent: true,
opacity: 0.22
})
);
scene.add(grid);
const axisMaterial = new THREE.MeshStandardMaterial({
color: 0x8ca2b7,
roughness: 0.75,
metalness: 0.05
});
function makeBar(length, thickness, material, z = -0.01) {
const bar = new THREE.Mesh(unitBoxGeometry, material);
bar.scale.set(length, thickness, thickness);
bar.position.z = z;
return bar;
}
const xAxis = makeBar(10.25, 0.045, axisMaterial);
xAxis.position.set(5.12, 0, -0.01);
scene.add(xAxis);
const yAxis = makeBar(12.25, 0.045, axisMaterial);
yAxis.position.set(0, 6.12, -0.01);
scene.add(yAxis);
const tickMaterial = new THREE.MeshBasicMaterial({ color: 0x70869c });
for (let x = 0; x <= 10; x++) {
const tick = new THREE.Mesh(unitBoxGeometry, tickMaterial);
tick.scale.set(0.035, x % 2 === 0 ? 0.19 : 0.11, 0.035);
tick.position.set(x, 0, 0.01);
scene.add(tick);
}
for (let y = 0; y <= 12; y++) {
const tick = new THREE.Mesh(unitBoxGeometry, tickMaterial);
tick.scale.set(y % 2 === 0 ? 0.19 : 0.11, 0.035, 0.035);
tick.position.set(0, y, 0.01);
scene.add(tick);
}
function makeTextSprite(text, color = "#91a4b8", width = 0.52) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 256, 128);
context.fillStyle = color;
context.font = "700 54px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 64);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
})
);
sprite.scale.set(width, width * 0.5, 1);
sprite.renderOrder = 10;
return sprite;
}
for (let x = 0; x <= 10; x += 2) {
const label = makeTextSprite(String(x));
label.position.set(x, -0.42, 0.03);
scene.add(label);
}
for (let y = 2; y <= 12; y += 2) {
const label = makeTextSprite(String(y));
label.position.set(-0.42, y, 0.03);
scene.add(label);
}
const xLabel = makeTextSprite("x", "#b6c7d8", 0.48);
xLabel.position.set(10.45, -0.46, 0.03);
scene.add(xLabel);
const yLabel = makeTextSprite("y", "#b6c7d8", 0.48);
yLabel.position.set(-0.44, 12.55, 0.03);
scene.add(yLabel);
// ------------------------------------------------------------
// Extrapolation shading and observed-support bracket
// ------------------------------------------------------------
const extrapolationMaterial = new THREE.MeshBasicMaterial({
color: colors.amber,
transparent: true,
opacity: 0.075,
depthWrite: false,
side: THREE.DoubleSide
});
const leftZone = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
extrapolationMaterial
);
leftZone.position.z = -0.13;
const rightZone = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
extrapolationMaterial
);
rightZone.position.z = -0.13;
scene.add(leftZone, rightZone);
const supportMaterial = new THREE.MeshBasicMaterial({
color: colors.mint,
transparent: true,
opacity: 0.9
});
const supportStrip = new THREE.Mesh(unitBoxGeometry, supportMaterial);
const supportCapA = new THREE.Mesh(unitBoxGeometry, supportMaterial);
const supportCapB = new THREE.Mesh(unitBoxGeometry, supportMaterial);
supportStrip.scale.set(1, 0.055, 0.055);
supportCapA.scale.set(0.055, 0.26, 0.055);
supportCapB.scale.set(0.055, 0.26, 0.055);
supportStrip.position.z = 0.02;
supportCapA.position.z = 0.02;
supportCapB.position.z = 0.02;
scene.add(supportStrip, supportCapA, supportCapB);
const supportLabel = makeTextSprite("observed x", "#5de4c4", 1.1);
supportLabel.position.set(5, 12.66, 0.03);
scene.add(supportLabel);
// ------------------------------------------------------------
// Fitted line: a solid in-support segment and dashed extensions
// ------------------------------------------------------------
const fitMaterial = new THREE.MeshBasicMaterial({ color: colors.mint });
const extrapolationLineMaterial = new THREE.MeshBasicMaterial({
color: colors.amber
});
const fitSolid = new THREE.Mesh(unitBoxGeometry, fitMaterial);
fitSolid.renderOrder = 3;
scene.add(fitSolid);
const dashPool = [];
for (let i = 0; i < 120; i++) {
const dash = new THREE.Mesh(unitBoxGeometry, extrapolationLineMaterial);
dash.visible = false;
dash.renderOrder = 3;
dashPool.push(dash);
scene.add(dash);
}
function setBarBetween(mesh, a, b, thickness = 0.055, depth = 0.055) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const length = Math.hypot(dx, dy);
mesh.visible = length > 0.0001;
mesh.position.set(
(a.x + b.x) * 0.5,
(a.y + b.y) * 0.5,
0.15
);
mesh.rotation.z = Math.atan2(dy, dx);
mesh.scale.set(length, thickness, depth);
}
function clipSegmentToChart(a, b) {
let t0 = 0;
let t1 = 1;
const dx = b.x - a.x;
const dy = b.y - a.y;
const p = [-dx, dx, -dy, dy];
const q = [
a.x - bounds.minX,
bounds.maxX - a.x,
a.y - bounds.minY,
bounds.maxY - a.y
];
for (let i = 0; i < 4; i++) {
if (Math.abs(p[i]) < 1e-10) {
if (q[i] < 0) return null;
continue;
}
const ratio = q[i] / p[i];
if (p[i] < 0) {
t0 = Math.max(t0, ratio);
} else {
t1 = Math.min(t1, ratio);
}
if (t0 > t1) return null;
}
return {
a: {
x: a.x + t0 * dx,
y: a.y + t0 * dy,
z: 0.15
},
b: {
x: a.x + t1 * dx,
y: a.y + t1 * dy,
z: 0.15
}
};
}
function drawDashedSegment(a, b) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const length = Math.hypot(dx, dy);
if (length < 0.001) return;
const count = Math.max(1, Math.ceil(length / 0.48));
const spacing = length / count;
const dashLength = spacing * 0.55;
const angle = Math.atan2(dy, dx);
for (let i = 0; i < count; i++) {
const dash = dashPool.shift();
const start = i * spacing + (spacing - dashLength) * 0.5;
const end = start + dashLength;
dash.visible = true;
dash.position.set(
a.x + (Math.cos(angle) * (start + end)) * 0.5,
a.y + (Math.sin(angle) * (start + end)) * 0.5,
0.15
);
dash.rotation.z = angle;
dash.scale.set(dashLength, 0.045, 0.045);
}
}
// ------------------------------------------------------------
// Selection indicator
// ------------------------------------------------------------
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.035, 6, 24),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
selectionRing.visible = false;
selectionRing.renderOrder = 8;
scene.add(selectionRing);
// ------------------------------------------------------------
// Data-point objects
// ------------------------------------------------------------
function createPointVisual(point) {
const markerMaterial = new THREE.MeshStandardMaterial({
color: point.outlier ? colors.amber : colors.point,
emissive: 0x000000,
emissiveIntensity: 0.8,
roughness: 0.48,
metalness: 0.06,
flatShading: true
});
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
marker.position.set(point.x, point.y, bounds.pointZ);
marker.userData.pointId = point.id;
marker.renderOrder = 6;
const stem = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(point.x, point.y, 0.015),
new THREE.Vector3(point.x, point.y, bounds.pointZ)
]),
stemMaterial
);
const shadow = new THREE.Mesh(shadowGeometry, shadowMaterial);
shadow.position.set(point.x, point.y, 0.018);
const residualLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(point.x, point.y, 0.62),
new THREE.Vector3(point.x, point.y, 0.62)
]),
new THREE.LineBasicMaterial({ color: colors.coral })
);
const residualCap = new THREE.Mesh(
residualCapGeometry,
new THREE.MeshBasicMaterial({ color: colors.coral })
);
residualLine.renderOrder = 7;
residualCap.renderOrder = 7;
pointGroup.add(marker, stem, shadow);
residualGroup.add(residualLine, residualCap);
const visual = {
marker,
stem,
shadow,
residualLine,
residualCap
};
pointVisuals.set(point.id, visual);
markerMeshes.push(marker);
return visual;
}
function clearPointVisuals() {
for (const point of data) {
const visual = pointVisuals.get(point.id);
if (!visual) continue;
visual.marker.material.dispose();
visual.stem.geometry.dispose();
visual.residualLine.geometry.dispose();
visual.residualLine.material.dispose();
visual.residualCap.material.dispose();
}
pointGroup.clear();
residualGroup.clear();
pointVisuals.clear();
markerMeshes.length = 0;
}
// ------------------------------------------------------------
// Statistics
// ------------------------------------------------------------
function computeModel() {
const n = data.length;
const meanX = data.reduce((sum, p) => sum + p.x, 0) / n;
const meanY = data.reduce((sum, p) => sum + p.y, 0) / n;
let sxx = 0;
let syy = 0;
let sxy = 0;
for (const point of data) {
const dx = point.x - meanX;
const dy = point.y - meanY;
sxx += dx * dx;
syy += dy * dy;
sxy += dx * dy;
}
const slope = sxx > 1e-12 ? sxy / sxx : 0;
const intercept = meanY - slope * meanX;
const denominator = Math.sqrt(sxx * syy);
const r = denominator > 1e-12
? Math.max(-1, Math.min(1, sxy / denominator))
: 0;
const fitted = data.map((point) => intercept + slope * point.x);
const residuals = data.map((point, index) => point.y - fitted[index]);
const mae = residuals.reduce((sum, value) => sum + Math.abs(value), 0) / n;
const rmse = Math.sqrt(
residuals.reduce((sum, value) => sum + value * value, 0) / n
);
return {
n,
meanX,
meanY,
slope,
intercept,
r,
r2: r * r,
fitted,
residuals,
mae,
rmse,
minX: Math.min(...data.map((point) => point.x)),
maxX: Math.max(...data.map((point) => point.x))
};
}
function residualColor(residual) {
if (Math.abs(residual) < 0.08) return colors.mint;
return residual > 0 ? colors.coral : colors.blue;
}
function formatSigned(value, digits = 2) {
if (value >= 0) return `+${value.toFixed(digits)}`;
return value.toFixed(digits);
}
function associationDescription(r) {
const strength = Math.abs(r) >= 0.75
? "strong"
: Math.abs(r) >= 0.45
? "moderate"
: Math.abs(r) >= 0.2
? "weak"
: "little";
if (strength === "little") {
return "Little linear association is visible in these data.";
}
const direction = r > 0 ? "positive" : "negative";
return `The sample shows a ${strength} ${direction} linear association.`;
}
function updateFitVisuals() {
const minX = model.minX;
const maxX = model.maxX;
const inSupport = clipSegmentToChart(
{ x: minX, y: model.intercept + model.slope * minX },
{ x: maxX, y: model.intercept + model.slope * maxX }
);
if (inSupport) {
setBarBetween(fitSolid, inSupport.a, inSupport.b, 0.065, 0.07);
} else {
fitSolid.visible = false;
}
dashPool.forEach((dash) => {
dash.visible = false;
});
const leftExtension = clipSegmentToChart(
{ x: bounds.minX, y: model.intercept + model.slope * bounds.minX },
{ x: minX, y: model.intercept + model.slope * minX }
);
const rightExtension = clipSegmentToChart(
{ x: maxX, y: model.intercept + model.slope * maxX },
{ x: bounds.maxX, y: model.intercept + model.slope * bounds.maxX }
);
if (leftExtension) drawDashedSegment(leftExtension.a, leftExtension.b);
if (rightExtension) drawDashedSegment(rightExtension.a, rightExtension.b);
}
function updateExtrapolationVisuals() {
const minX = model.minX;
const maxX = model.maxX;
leftZone.visible = minX > 0.001;
rightZone.visible = maxX < bounds.maxX - 0.001;
leftZone.scale.set(minX, bounds.maxY - bounds.minY, 1);
leftZone.position.set(
bounds.minX + minX * 0.5,
(bounds.minY + bounds.maxY) * 0.5,
-0.13
);
rightZone.scale.set(
bounds.maxX - maxX,
bounds.maxY - bounds.minY,
1
);
rightZone.position.set(
maxX + (bounds.maxX - maxX) * 0.5,
(bounds.minY + bounds.maxY) * 0.5,
-0.13
);
const supportWidth = Math.max(0.001, maxX - minX);
supportStrip.scale.set(supportWidth, 0.055, 0.055);
supportStrip.position.set((minX + maxX) * 0.5, 12.28, 0.02);
supportCapA.position.set(minX, 12.28, 0.02);
supportCapB.position.set(maxX, 12.28, 0.02);
supportLabel.position.set((minX + maxX) * 0.5, 12.67, 0.03);
}
function updatePointAndResidualVisuals() {
for (let index = 0; index < data.length; index++) {
const point = data[index];
const visual = pointVisuals.get(point.id);
if (!visual) continue;
const fitted = model.fitted[index];
const residual = model.residuals[index];
const color = residualColor(residual);
visual.marker.position.set(point.x, point.y, bounds.pointZ);
visual.marker.scale.setScalar(point.outlier ? 1.18 : 1);
visual.stem.geometry.setFromPoints([
new THREE.Vector3(point.x, point.y, 0.015),
new THREE.Vector3(point.x, point.y, bounds.pointZ)
]);
visual.shadow.position.set(point.x, point.y, 0.018);
visual.residualLine.geometry.setFromPoints([
new THREE.Vector3(point.x, fitted, 0.62),
new THREE.Vector3(point.x, point.y, 0.62)
]);
visual.residualLine.material.color.setHex(color);
visual.residualCap.material.color.setHex(color);
visual.residualCap.position.set(point.x, fitted, 0.62);
visual.residualLine.visible = ui.toggleResiduals.checked;
visual.residualCap.visible = ui.toggleResiduals.checked;
const isHovered = hoveredPoint === point;
const isSelected = selectedId === point.id;
visual.marker.material.emissive.setHex(
isSelected ? 0x176658 : isHovered ? 0x183b4a : 0x000000
);
visual.marker.material.emissiveIntensity = isSelected ? 1.15 : 0.7;
}
const selected = data.find((point) => point.id === selectedId);
selectionRing.visible = Boolean(selected);
if (selected) {
selectionRing.position.set(
selected.x,
selected.y,
bounds.pointZ + 0.015
);
}
}
function updateStats() {
ui.rValue.textContent = model.r.toFixed(2);
ui.r2Value.textContent = model.r2.toFixed(2);
ui.slopeValue.textContent = model.slope.toFixed(2);
ui.nValue.textContent = model.n;
const associationColor = model.r >= 0 ? "#5de4c4" : "#ff7377";
ui.rValue.style.color = associationColor;
ui.rMeterFill.style.width = `${Math.abs(model.r) * 100}%`;
ui.rMeterFill.style.background = associationColor;
ui.equation.textContent =
`ŷ = ${model.intercept.toFixed(2)} ${model.slope >= 0 ? "+" : "−"} ` +
`${Math.abs(model.slope).toFixed(2)}x`;
ui.statusChip.textContent =
model.r > 0.2 ? "Positive" : model.r < -0.2 ? "Negative" : "Weak";
ui.statusChip.style.color = associationColor;
ui.statusChip.style.borderColor = `${associationColor}55`;
ui.statusChip.style.background = `${associationColor}12`;
ui.modelNote.textContent = associationDescription(model.r);
ui.maeValue.textContent = model.mae.toFixed(2);
ui.rmseValue.textContent = model.rmse.toFixed(2);
ui.residualList.innerHTML = data.map((point, index) => {
const residual = model.residuals[index];
const className =
Math.abs(residual) < 0.08 ? "near-zero" : residual > 0 ? "positive" : "negative";
return `
<div class="res-row">
<span>Point ${index + 1}${point.outlier ? " · added" : ""}</span>
<b class="${className}">${formatSigned(residual)}</b>
</div>
`;
}).join("");
ui.supportValue.textContent =
`${model.minX.toFixed(1)} to ${model.maxX.toFixed(1)}`;
const slopeDescription = Math.abs(model.slope) < 0.01
? "The fitted slope is nearly flat."
: `Within the observed range, a one-unit increase in x corresponds to a ` +
`${formatSigned(model.slope)} change in fitted y.`;
ui.extrapolationText.innerHTML =
`The observations cover <strong>x = ${model.minX.toFixed(1)}–${model.maxX.toFixed(1)}</strong>. ` +
`The shaded bands are outside that observed support. ` +
`${slopeDescription} Beyond the observed x-values, that rate is only an assumption, ` +
`so predictions there are extrapolations rather than interpolation.`;
ui.causationText.textContent =
"Also remember: correlation describes co-movement, not proof that changing x causes y to change.";
}
function updateAll() {
model = computeModel();
updateFitVisuals();
updateExtrapolationVisuals();
updatePointAndResidualVisuals();
updateStats();
scene.updateMatrixWorld(true);
}
// ------------------------------------------------------------
// Tooltip
// ------------------------------------------------------------
function showTooltip(point, event) {
const index = data.indexOf(point);
if (index < 0 || !model) return;
const residual = model.residuals[index];
tooltip.innerHTML = `
<strong>${point.outlier ? "Influential point" : "Observation"} ${index + 1}</strong>
<div class="tooltip-grid">
<span>Observed x</span><b>${point.x.toFixed(2)}</b>
<span>Observed y</span><b>${point.y.toFixed(2)}</b>
<span>Fitted ŷ</span><b>${model.fitted[index].toFixed(2)}</b>
<span>Residual</span><b>${formatSigned(residual)}</b>
</div>
`;
const rect = stage.getBoundingClientRect();
const width = 210;
const height = 128;
let left = event.clientX - rect.left + 14;
let top = event.clientY - rect.top + 14;
left = Math.max(8, Math.min(left, rect.width - width - 8));
top = Math.max(8, Math.min(top, rect.height - height - 8));
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
tooltip.style.display = "block";
}
function hideTooltip() {
tooltip.style.display = "none";
}
// ------------------------------------------------------------
// Custom camera controls and point dragging
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(5, 6.05, 0);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -bounds.pointZ);
const intersection = new THREE.Vector3();
let azimuth = 0;
let elevation = 0.22;
let zoomRadius = 17.5;
let minimumRadius = 14;
let interaction = null;
function updateCamera() {
const radius = Math.max(zoomRadius, minimumRadius);
const horizontalRadius = radius * Math.cos(elevation);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(azimuth),
cameraTarget.y + radius * Math.sin(elevation),
cameraTarget.z + horizontalRadius * Math.cos(azimuth)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
azimuth = 0;
elevation = 0.22;
zoomRadius = 17.5;
updateCamera();
}
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function hitTestPoint() {
const intersections = raycaster.intersectObjects(markerMeshes, false);
return intersections.length
? data.find((point) => point.id === intersections[0].object.userData.pointId)
: null;
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
canvas.focus({ preventScroll: true });
updatePointer(event);
const hit = hitTestPoint();
if (hit) {
selectedId = hit.id;
hoveredPoint = hit;
interaction = {
type: "point",
id: hit.id,
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
showTooltip(hit, event);
} else {
interaction = {
type: "orbit",
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
hideTooltip();
}
canvas.setPointerCapture(event.pointerId);
updateAll();
});
canvas.addEventListener("pointermove", (event) => {
if (!interaction) {
updatePointer(event);
const hit = hitTestPoint();
hoveredPoint = hit;
if (hit) {
showTooltip(hit, event);
canvas.style.cursor = "grab";
} else {
hideTooltip();
canvas.style.cursor = "grab";
}
updatePointAndResidualVisuals();
return;
}
if (interaction.type === "point") {
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, intersection)) {
const point = data.find((item) => item.id === interaction.id);
if (point) {
point.x = THREE.MathUtils.clamp(
intersection.x,
bounds.minX + 0.2,
bounds.maxX - 0.2
);
point.y = THREE.MathUtils.clamp(
intersection.y,
bounds.minY + 0.2,
bounds.maxY - 0.2
);
hoveredPoint = point;
updateAll();
showTooltip(point, event);
}
}
return;
}
const dx = event.clientX - interaction.lastX;
const dy = event.clientY - interaction.lastY;
interaction.lastX = event.clientX;
interaction.lastY = event.clientY;
azimuth -= dx * 0.006;
elevation = THREE.MathUtils.clamp(elevation + dy * 0.004, -0.3, 1.05);
updateCamera();
});
function endInteraction(event) {
if (!interaction) return;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
interaction = null;
canvas.style.cursor = "grab";
}
canvas.addEventListener("pointerup", endInteraction);
canvas.addEventListener("pointercancel", endInteraction);
canvas.addEventListener("pointerleave", () => {
if (!interaction) {
hoveredPoint = null;
hideTooltip();
updatePointAndResidualVisuals();
}
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
zoomRadius = THREE.MathUtils.clamp(
zoomRadius * Math.exp(event.deltaY * 0.001),
8,
45
);
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// Keyboard nudging for the selected point.
canvas.addEventListener("keydown", (event) => {
if (selectedId === null) return;
const point = data.find((item) => item.id === selectedId);
if (!point) return;
const step = event.shiftKey ? 0.5 : 0.1;
let handled = true;
switch (event.key) {
case "ArrowLeft":
point.x -= step;
break;
case "ArrowRight":
point.x += step;
break;
case "ArrowUp":
point.y += step;
break;
case "ArrowDown":
point.y -= step;
break;
case "Escape":
selectedId = null;
handled = true;
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
point.x = THREE.MathUtils.clamp(
point.x,
bounds.minX + 0.2,
bounds.maxX - 0.2
);
point.y = THREE.MathUtils.clamp(
point.y,
bounds.minY + 0.2,
bounds.maxY - 0.2
);
updateAll();
}
});
// ------------------------------------------------------------
// UI actions
// ------------------------------------------------------------
ui.addOutlier.addEventListener("click", () => {
const point = {
id: nextId++,
x: 5.3 + (nextId % 3) * 0.35,
y: 11.45,
outlier: true
};
data.push(point);
createPointVisual(point);
selectedId = point.id;
hoveredPoint = point;
updateAll();
});
ui.resetData.addEventListener("click", () => {
clearPointVisuals();
data = initialData.map((d) => ({ ...d }));
nextId = initialData.length + 1;
selectedId = null;
hoveredPoint = null;
hideTooltip();
for (const point of data) createPointVisual(point);
updateAll();
});
ui.resetView.addEventListener("click", resetCamera);
ui.toggleResiduals.addEventListener("change", () => {
updatePointAndResidualVisuals();
});
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
const halfVerticalFov = THREE.MathUtils.degToRad(camera.fov * 0.5);
const verticalFitRadius = 13.3 / (2 * Math.tan(halfVerticalFov));
const horizontalFitRadius =
11.8 / (2 * Math.tan(halfVerticalFov) * camera.aspect);
minimumRadius = Math.max(verticalFitRadius, horizontalFitRadius);
updateCamera();
}
new ResizeObserver(resize).observe(stage);
window.addEventListener("resize", resize);
for (const point of data) createPointVisual(point);
updateAll();
resize();
canvas.style.cursor = "grab";
function animate() {
requestAnimationFrame(animate);
updateCamera();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```