Prompt specification
Build or customize the Three.js 3D scene "Similar correlation different structures" 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: Similar correlation different structures
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/similar-correlation-different-structures-x1786
Scene Description Prompt:
Compare stylized plots of synthetic datasets with similar correlations but different shapes and outliers. Build one HTML file using Three.js from cdnjs.
Working Three.js Starter (similar-correlation-different-structures-x1786):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Same r. Different stories.</title>
<style>
:root {
color-scheme: dark;
--bg: #080b11;
--panel: #10151f;
--panel-2: #141b27;
--text: #f2f4f7;
--muted: #929dad;
--line: rgba(255, 255, 255, 0.1);
--accent: #f3c969;
--radius: 22px;
}
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at 12% 0%, rgba(77, 104, 150, 0.2), transparent 32rem),
radial-gradient(circle at 88% 18%, rgba(242, 201, 105, 0.08), transparent 26rem),
var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
}
body::before {
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
content: "";
opacity: 0.22;
background-image:
linear-gradient(rgba(255, 255, 255, 0.025) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.025) 1px, transparent 1px);
background-size: 52px 52px;
mask-image: linear-gradient(to bottom, black, transparent 75%);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.page {
width: min(1500px, calc(100% - 40px));
margin: 0 auto;
padding: 42px 0 56px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 40px;
padding: 22px 0 42px;
}
.eyebrow,
.section-kicker,
.card-kicker {
color: var(--muted);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 22px;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 18px rgba(243, 201, 105, 0.65);
content: "";
}
h1 {
max-width: 950px;
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(3.5rem, 8.3vw, 7.7rem);
font-weight: 400;
line-height: 0.83;
letter-spacing: -0.068em;
}
h1 em {
color: var(--accent);
font-weight: 400;
}
.hero-copy {
max-width: 720px;
margin: 28px 0 0;
color: #aeb7c4;
font-size: clamp(1rem, 1.6vw, 1.25rem);
line-height: 1.65;
}
.hero-stat {
display: grid;
justify-items: center;
min-width: 230px;
padding: 12px 0 4px;
}
.orbit-stat {
position: relative;
display: grid;
width: 210px;
height: 210px;
place-items: center;
border: 1px solid rgba(243, 201, 105, 0.24);
border-radius: 50%;
background:
radial-gradient(circle, rgba(243, 201, 105, 0.08), transparent 64%),
rgba(255, 255, 255, 0.015);
}
.orbit-stat::before,
.orbit-stat::after {
position: absolute;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 50%;
content: "";
}
.orbit-stat::before {
inset: 15px;
}
.orbit-stat::after {
inset: 39px;
border-color: rgba(243, 201, 105, 0.18);
}
.orbit-dot {
position: absolute;
top: 22px;
right: 34px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 18px var(--accent);
}
.orbit-content {
position: relative;
z-index: 1;
text-align: center;
}
.orbit-content small {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 0.66rem;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.orbit-content strong {
font-family: Georgia, "Times New Roman", serif;
font-size: 3.1rem;
font-weight: 400;
letter-spacing: -0.06em;
}
.orbit-content strong i {
margin-right: 3px;
color: var(--accent);
font-size: 1.35rem;
}
.hero-stat-note {
margin: 14px 0 0;
color: var(--muted);
font-size: 0.74rem;
text-align: center;
}
.control-deck {
position: sticky;
top: 12px;
z-index: 20;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 14px 24px;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(13, 18, 27, 0.86);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
}
.control {
display: grid;
grid-template-columns: auto minmax(105px, 170px) auto;
align-items: center;
gap: 10px;
}
.control label,
.control-title {
color: #c6cdd6;
font-size: 0.76rem;
font-weight: 700;
letter-spacing: 0.035em;
white-space: nowrap;
}
.control output {
min-width: 45px;
color: var(--accent);
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 0.76rem;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 10px;
accent-color: var(--accent);
cursor: ew-resize;
}
.deck-spacer {
flex: 1;
}
.switch {
display: inline-flex;
align-items: center;
gap: 9px;
color: #c6cdd6;
font-size: 0.78rem;
font-weight: 700;
cursor: pointer;
user-select: none;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch-track {
position: relative;
width: 37px;
height: 21px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 999px;
background: #222a37;
transition: 160ms ease;
}
.switch-track::after {
position: absolute;
top: 3px;
left: 3px;
width: 13px;
height: 13px;
border-radius: 50%;
background: #7c8796;
content: "";
transition: 160ms ease;
}
.switch input:checked + .switch-track {
border-color: rgba(243, 201, 105, 0.35);
background: rgba(243, 201, 105, 0.18);
}
.switch input:checked + .switch-track::after {
left: 19px;
background: var(--accent);
box-shadow: 0 0 12px rgba(243, 201, 105, 0.5);
}
.button {
min-height: 38px;
padding: 0 15px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 11px;
background: rgba(255, 255, 255, 0.045);
font-size: 0.76rem;
font-weight: 750;
cursor: pointer;
transition: 150ms ease;
}
.button:hover {
border-color: rgba(243, 201, 105, 0.42);
background: rgba(243, 201, 105, 0.1);
transform: translateY(-1px);
}
.button.primary {
border-color: var(--accent);
background: var(--accent);
color: #17130a;
}
.button.primary:hover {
background: #ffda83;
}
.section-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
margin: 48px 0 20px;
}
.section-heading h2 {
margin: 6px 0 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(2rem, 4vw, 3.8rem);
font-weight: 400;
letter-spacing: -0.045em;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 10px 18px;
color: var(--muted);
font-size: 0.72rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #f3c969;
box-shadow: 0 0 12px currentColor;
}
.legend-line {
width: 24px;
border-top: 1px dashed #aab3c0;
}
.plot-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
}
.plot-card {
position: relative;
min-width: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent 42%),
var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.14);
}
.plot-card::before {
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: 2;
height: 3px;
background: var(--accent);
box-shadow: 0 0 22px color-mix(in srgb, var(--accent) 45%, transparent);
content: "";
}
.card-header {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: 16px;
align-items: start;
padding: 25px 25px 19px;
}
.card-number {
display: grid;
width: 38px;
height: 38px;
place-items: center;
border: 1px solid color-mix(in srgb, var(--accent) 32%, transparent);
border-radius: 50%;
color: var(--accent);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.71rem;
}
.card-copy h3 {
margin: 4px 0 7px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(1.35rem, 2.1vw, 1.9rem);
font-weight: 400;
letter-spacing: -0.035em;
}
.card-copy p {
max-width: 540px;
margin: 0;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.55;
}
.r-pill {
display: grid;
min-width: 68px;
justify-items: end;
}
.r-pill span {
color: var(--muted);
font-family: Georgia, "Times New Roman", serif;
font-size: 0.85rem;
font-style: italic;
}
.r-pill strong {
color: var(--accent);
font-family: Georgia, "Times New Roman", serif;
font-size: 1.75rem;
font-weight: 400;
letter-spacing: -0.05em;
}
.plot-stage {
position: relative;
height: clamp(280px, 30vw, 360px);
overflow: hidden;
border-top: 1px solid rgba(255, 255, 255, 0.055);
border-bottom: 1px solid rgba(255, 255, 255, 0.055);
background:
radial-gradient(circle at 50% 45%, rgba(255, 255, 255, 0.035), transparent 52%),
#0c111a;
cursor: grab;
touch-action: none;
}
.plot-stage.is-dragging {
cursor: grabbing;
}
.plot-stage canvas {
position: absolute;
inset: 0;
z-index: 1;
display: block;
width: 100%;
height: 100%;
outline: none;
}
.view-hint {
position: absolute;
right: 13px;
bottom: 12px;
z-index: 3;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
color: #6f7b8c;
background: rgba(8, 11, 17, 0.66);
font-size: 0.64rem;
pointer-events: none;
}
.point-tooltip {
position: absolute;
z-index: 5;
display: grid;
min-width: 142px;
gap: 3px;
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 10px;
background: rgba(8, 11, 17, 0.92);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
pointer-events: none;
backdrop-filter: blur(10px);
}
.point-tooltip span {
color: var(--muted);
font-size: 0.62rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.point-tooltip b {
color: var(--text);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.72rem;
font-weight: 500;
}
[hidden] {
display: none !important;
}
.card-footer {
display: grid;
grid-template-columns: repeat(3, 1fr);
padding: 17px 25px 20px;
}
.metric {
display: grid;
gap: 4px;
padding-right: 15px;
border-right: 1px solid rgba(255, 255, 255, 0.07);
}
.metric + .metric {
padding-left: 18px;
}
.metric:last-child {
border-right: 0;
}
.metric span {
color: var(--muted);
font-size: 0.65rem;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.78rem;
font-weight: 500;
}
.takeaways {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 18px;
margin-top: 18px;
}
.takeaway {
position: relative;
overflow: hidden;
padding: 26px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255, 255, 255, 0.025);
}
.takeaway::after {
position: absolute;
right: -30px;
bottom: -45px;
width: 130px;
height: 130px;
border: 1px solid rgba(243, 201, 105, 0.12);
border-radius: 50%;
content: "";
}
.takeaway-number {
color: var(--accent);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.68rem;
}
.takeaway h3 {
margin: 13px 0 9px;
font-family: Georgia, "Times New Roman", serif;
font-size: 1.45rem;
font-weight: 400;
letter-spacing: -0.03em;
}
.takeaway p {
position: relative;
z-index: 1;
margin: 0;
color: var(--muted);
font-size: 0.79rem;
line-height: 1.65;
}
.page-footer {
display: flex;
justify-content: space-between;
gap: 24px;
margin-top: 42px;
padding-top: 20px;
border-top: 1px solid var(--line);
color: #6f7988;
font-size: 0.68rem;
line-height: 1.6;
}
.page-footer p {
max-width: 740px;
margin: 0;
}
.page-footer code {
color: #aeb7c4;
}
@media (max-width: 960px) {
.hero {
grid-template-columns: 1fr;
}
.hero-stat {
justify-items: start;
}
.orbit-stat {
width: 180px;
height: 180px;
}
.control-deck {
position: relative;
top: 0;
}
.deck-spacer {
display: none;
}
.plot-grid {
grid-template-columns: 1fr;
}
.takeaways {
grid-template-columns: 1fr;
}
}
@media (max-width: 620px) {
.page {
width: min(100% - 24px, 1500px);
padding-top: 24px;
}
.hero {
padding-top: 10px;
}
.hero-stat {
min-width: 0;
}
.orbit-stat {
width: 160px;
height: 160px;
}
.orbit-content strong {
font-size: 2.5rem;
}
.control-deck {
display: grid;
grid-template-columns: 1fr;
}
.control {
grid-template-columns: 105px minmax(80px, 1fr) 45px;
}
.deck-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button {
width: 100%;
}
.section-heading {
display: block;
}
.legend {
justify-content: flex-start;
margin-top: 14px;
}
.card-header {
grid-template-columns: auto minmax(0, 1fr);
padding: 21px 18px 17px;
}
.r-pill {
grid-column: 2;
grid-row: 1;
justify-items: start;
margin-left: 54px;
}
.card-footer {
padding: 15px 18px 18px;
}
.metric + .metric {
padding-left: 11px;
}
.page-footer {
display: block;
}
.page-footer p + p {
margin-top: 12px;
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
transition-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<main class="page">
<header class="hero">
<div>
<div class="eyebrow">Synthetic data observatory · Study 04</div>
<h1>Same <em>r</em>.<br />Different stories.</h1>
<p class="hero-copy">
Four synthetic datasets share nearly the same Pearson correlation.
Their geometry does not: one bends, one clusters, and one hides its
story in a handful of leverage points.
</p>
</div>
<aside class="hero-stat" aria-label="Shared target correlation">
<div class="orbit-stat">
<span class="orbit-dot"></span>
<div class="orbit-content">
<small>Shared target</small>
<strong><i>r</i> <span id="heroR">0.78</span></strong>
</div>
</div>
<p class="hero-stat-note">One coefficient · four distributions</p>
</aside>
</header>
<section class="control-deck" aria-label="Dataset controls">
<div class="control">
<label for="sampleRange">Sample size</label>
<input id="sampleRange" type="range" min="40" max="140" step="4" value="84" />
<output id="sampleOutput" for="sampleRange">84</output>
</div>
<div class="control">
<label for="corrRange">Correlation</label>
<input id="corrRange" type="range" min="0.55" max="0.90" step="0.01" value="0.78" />
<output id="corrOutput" for="corrRange">0.78</output>
</div>
<div class="control">
<label for="outlierRange">Outliers</label>
<input id="outlierRange" type="range" min="0.4" max="2.0" step="0.1" value="1.1" />
<output id="outlierOutput" for="outlierRange">1.1×</output>
</div>
<div class="deck-spacer"></div>
<label class="switch" title="Show the least-squares fit">
<input id="fitToggle" type="checkbox" checked />
<span class="switch-track"></span>
<span>Show fit</span>
</label>
<div class="deck-actions">
<button class="button" id="resetViews" type="button">Reset views</button>
<button class="button primary" id="newSamples" type="button">New samples ↗</button>
</div>
</section>
<div class="section-heading">
<div>
<div class="section-kicker">Four views of the same statistic</div>
<h2>The coefficient is not the picture.</h2>
</div>
<div class="legend" aria-label="Plot legend">
<span class="legend-item"><i class="legend-dot"></i> Observations</span>
<span class="legend-item"><i class="legend-line"></i> Least-squares fit</span>
<span class="legend-item">Shared standardized scale</span>
</div>
</div>
<section id="plotGrid" class="plot-grid" aria-label="Synthetic scatter plot comparison"></section>
<section class="takeaways" aria-label="Interpretation notes">
<article class="takeaway">
<span class="takeaway-number">01 / PEARSON</span>
<h3>Direction is not form.</h3>
<p>
All four panels are constructed near <strong id="insightR">r = 0.78</strong>.
Correlation confirms a shared linear tendency, but it cannot tell a
straight cloud from a crescent.
</p>
</article>
<article class="takeaway">
<span class="takeaway-number">02 / RANK</span>
<h3>The rank gap exposes shape.</h3>
<p>
Spearman’s ρ ranges from <strong id="insightRho">—</strong> across these
panels. A large gap between r and ρ is a clue that linear correlation
is summarizing a changing relationship.
</p>
</article>
<article class="takeaway">
<span class="takeaway-number">03 / LEVERAGE</span>
<h3>A few points can own the line.</h3>
<p>
The outlier panel keeps the same correlation while adding
<strong id="insightOutlier">— high-leverage observations</strong>.
The central cloud remains quiet, but the fitted story becomes fragile.
</p>
</article>
</section>
<footer class="page-footer">
<p>
The third dimension is a viewing aid only: all statistics are calculated
from the original two-dimensional x/y values. Drag any panel to tilt the
camera and scroll to zoom. Hover an observation for its coordinates.
</p>
<p>
<code>Three.js r160</code> · core module only · direct camera controls
</p>
</footer>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector, root = document) => root.querySelector(selector);
const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
const DOMAIN = 3.2;
const MAX_POINTS = 160;
const state = {
n: 84,
r: 0.78,
outlierStrength: 1.1,
seed: 2404,
showFit: true
};
const metadata = [
{
name: "The clean band",
kicker: "Stable cloud",
description:
"A compact linear cloud with symmetric residuals. This is correlation behaving as expected.",
accent: "#58d9bc"
},
{
name: "The hidden crescent",
kicker: "Curved regime",
description:
"A nonlinear arc produces nearly the same linear correlation as the clean band.",
accent: "#a98bfa"
},
{
name: "Three populations",
kicker: "Clustered mixture",
description:
"Three latent groups align overall, while the global coefficient conceals local structure.",
accent: "#ff8b6b"
},
{
name: "The leverage points",
kicker: "Core plus outliers",
description:
"A quiet core is surrounded by influential observations that strongly affect the fitted line.",
accent: "#f3c969"
}
];
const grid = $("#plotGrid");
grid.innerHTML = metadata
.map(
(meta, index) => `
<article class="plot-card" style="--accent:${meta.accent}">
<header class="card-header">
<div class="card-number">0${index + 1}</div>
<div class="card-copy">
<div class="card-kicker">${meta.kicker}</div>
<h3>${meta.name}</h3>
<p>${meta.description}</p>
</div>
<div class="r-pill">
<span>Pearson r</span>
<strong data-role="r">0.00</strong>
</div>
</header>
<div
class="plot-stage"
role="img"
aria-label="${meta.name}. Interactive three-dimensional view of a synthetic scatter plot."
>
<div class="view-hint">drag to tilt · scroll to zoom</div>
<div class="point-tooltip" hidden></div>
</div>
<footer class="card-footer">
<div class="metric">
<span>Spearman ρ</span>
<strong data-role="rho">—</strong>
</div>
<div class="metric">
<span>Rank gap</span>
<strong data-role="gap">—</strong>
</div>
<div class="metric">
<span>Observations</span>
<strong data-role="count">—</strong>
</div>
</footer>
</article>
`
)
.join("");
const stages = $$(".plot-stage");
function mulberry32(seed) {
return function random() {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function gaussian(random) {
let u = 0;
let v = 0;
while (u === 0) u = random();
while (v === 0) v = random();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function standardize(values) {
const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
const variance =
values.reduce((sum, value) => sum + (value - mean) ** 2, 0) /
values.length;
const sd = Math.sqrt(variance) || 1;
return values.map((value) => (value - mean) / sd);
}
function pearson(a, b) {
const n = Math.min(a.length, b.length);
const meanA = a.reduce((sum, value) => sum + value, 0) / n;
const meanB = b.reduce((sum, value) => sum + value, 0) / n;
let covariance = 0;
let varianceA = 0;
let varianceB = 0;
for (let i = 0; i < n; i++) {
const da = a[i] - meanA;
const db = b[i] - meanB;
covariance += da * db;
varianceA += da * da;
varianceB += db * db;
}
const result =
covariance / (Math.sqrt(varianceA) * Math.sqrt(varianceB) || 1);
return Math.max(-1, Math.min(1, result));
}
function ranks(values) {
const indexed = values
.map((value, index) => ({ value, index }))
.sort((a, b) => a.value - b.value);
const result = Array(values.length);
for (let start = 0; start < indexed.length; ) {
let end = start + 1;
while (
end < indexed.length &&
indexed[end].value === indexed[start].value
) {
end++;
}
const averageRank = (start + 1 + end) / 2;
for (let i = start; i < end; i++) {
result[indexed[i].index] = averageRank;
}
start = end;
}
return result;
}
function spearman(a, b) {
return pearson(ranks(a), ranks(b));
}
function median(values) {
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2
? sorted[middle]
: (sorted[middle - 1] + sorted[middle]) / 2;
}
function buildDataset(
rawX,
rawZ,
targetCorrelation,
groups = [],
outlierFlags = []
) {
const x = standardize(rawX);
const z = standardize(rawZ);
const xSquared = x.reduce((sum, value) => sum + value * value, 0);
const projection =
z.reduce((sum, value, index) => sum + value * x[index], 0) /
(xSquared || 1);
const orthogonalZ = standardize(
z.map((value, index) => value - projection * x[index])
);
const residualWeight = Math.sqrt(
Math.max(0, 1 - targetCorrelation * targetCorrelation)
);
return x.map((value, index) => ({
x: value,
y:
targetCorrelation * value +
residualWeight * orthogonalZ[index],
group: groups[index] ?? index,
outlier: outlierFlags[index] ?? false
}));
}
function buildDatasets() {
const n = state.n;
const datasets = [];
// 1. Clean linear cloud.
{
const random = mulberry32(state.seed + 11);
const rawX = [];
const rawZ = [];
for (let i = 0; i < n; i++) {
rawX.push(-2.6 + random() * 5.2);
rawZ.push(gaussian(random) * 0.42);
}
datasets.push(buildDataset(rawX, rawZ, state.r));
}
// 2. Nonlinear crescent.
{
const random = mulberry32(state.seed + 29);
const rawX = [];
const rawZ = [];
for (let i = 0; i < n; i++) {
const x = -3.05 + random() * 6.1;
rawX.push(x);
rawZ.push(
1.15 * Math.sin(x * 1.05) +
0.12 * Math.cos(x * 2.3) +
gaussian(random) * 0.3
);
}
datasets.push(buildDataset(rawX, rawZ, state.r));
}
// 3. Three-cluster mixture.
{
const random = mulberry32(state.seed + 47);
const centers = [-2.1, -0.1, 2.0];
const offsets = [0.95, -0.8, 0.35];
const rawX = [];
const rawZ = [];
const groups = [];
for (let i = 0; i < n; i++) {
const group = Math.floor(random() * 3);
groups.push(group);
rawX.push(centers[group] + gaussian(random) * 0.58);
rawZ.push(offsets[group] + gaussian(random) * 0.43);
}
datasets.push(buildDataset(rawX, rawZ, state.r, groups));
}
// 4. Quiet core plus high-leverage outliers.
{
const random = mulberry32(state.seed + 83);
const outlierCount = Math.max(5, Math.round(n * 0.09));
const coreCount = n - outlierCount;
const rawX = [];
const rawZ = [];
const outlierFlags = [];
for (let i = 0; i < coreCount; i++) {
rawX.push(-2.55 + random() * 5.1);
rawZ.push(gaussian(random) * 0.48);
outlierFlags.push(false);
}
for (let i = 0; i < outlierCount; i++) {
const side = i % 2 === 0 ? -1 : 1;
if (i === outlierCount - 1) {
// A mostly vertical leverage point.
rawX.push(0.25 + random() * 0.45);
rawZ.push(4.2 * state.outlierStrength);
} else {
rawX.push(side * (2.9 + random() * 0.95));
rawZ.push(
side * (2.3 * state.outlierStrength + random() * 0.75)
);
}
outlierFlags.push(true);
}
datasets.push(
buildDataset(rawX, rawZ, state.r, [], outlierFlags)
);
}
return datasets;
}
function makeTextSprite(text, color = "#7f8b9d") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 80;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
context.font = "600 36px ui-monospace, SFMono-Regular, Consolas, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 40);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.72, 0.225, 1);
sprite.renderOrder = 10;
return sprite;
}
function makeLine(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => new THREE.Vector3(...point))
);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
});
return new THREE.Line(geometry, material);
}
class ScatterPlot {
constructor(stage, accent) {
this.stage = stage;
this.accent = new THREE.Color(accent);
this.data = [];
this.dragging = false;
this.pointerId = null;
this.lastPointer = { x: 0, y: 0 };
this.theta = -0.12;
this.phi = 0.07;
this.radius = 12;
this.targetTheta = this.theta;
this.targetPhi = this.phi;
this.targetRadius = this.radius;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
100
);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
this.renderer.setClearColor(0x000000, 0);
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.08;
this.canvas = this.renderer.domElement;
this.canvas.setAttribute("aria-hidden", "true");
this.stage.appendChild(this.canvas);
this.tooltip = $(".point-tooltip", this.stage);
this.scene.add(new THREE.AmbientLight(0xffffff, 1.4));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(-4, 5, 8);
this.scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(this.accent, 1.5);
rimLight.position.set(5, -3, 5);
this.scene.add(rimLight);
this.createAxes();
this.createPoints();
this.bindControls();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(this.stage);
this.resize();
}
createAxes() {
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(DOMAIN * 2.15, DOMAIN * 2.15),
new THREE.MeshBasicMaterial({
color: 0x0c121c,
transparent: true,
opacity: 0.82,
depthWrite: false
})
);
plane.position.z = -0.3;
this.scene.add(plane);
const grid = new THREE.GridHelper(
DOMAIN * 2,
8,
0x536177,
0x263143
);
grid.rotation.x = Math.PI / 2;
grid.position.z = -0.22;
grid.material.transparent = true;
grid.material.opacity = 0.42;
grid.material.depthWrite = false;
this.scene.add(grid);
const axisX = makeLine(
[
[-DOMAIN, 0, -0.16],
[DOMAIN, 0, -0.16]
],
0x8491a5,
0.55
);
const axisY = makeLine(
[
[0, -DOMAIN, -0.16],
[0, DOMAIN, -0.16]
],
0x8491a5,
0.55
);
this.scene.add(axisX, axisY);
for (const value of [-3, -1.5, 0, 1.5, 3]) {
this.scene.add(
makeLine(
[
[value - 0.055, 0, -0.12],
[value + 0.055, 0, -0.12]
],
0x778397,
0.55
),
makeLine(
[
[0, value - 0.055, -0.12],
[0, value + 0.055, -0.12]
],
0x778397,
0.55
)
);
}
const xLabel = makeTextSprite("X / SD");
xLabel.position.set(DOMAIN + 0.43, -0.25, 0.02);
const yLabel = makeTextSprite("Y / SD");
yLabel.position.set(-0.42, DOMAIN + 0.43, 0.02);
this.scene.add(xLabel, yLabel);
this.fitMaterial = new THREE.LineDashedMaterial({
color: 0xd9e1ea,
dashSize: 0.18,
gapSize: 0.12,
transparent: true,
opacity: 0.44,
depthTest: false
});
this.fitLine = new THREE.Line(
new THREE.BufferGeometry(),
this.fitMaterial
);
this.fitLine.renderOrder = 4;
this.scene.add(this.fitLine);
}
createPoints() {
this.pointGeometry = new THREE.IcosahedronGeometry(0.075, 1);
this.pointMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.28,
metalness: 0.12,
emissive: this.accent,
emissiveIntensity: 0.11
});
this.pointMesh = new THREE.InstancedMesh(
this.pointGeometry,
this.pointMaterial,
MAX_POINTS
);
this.pointMesh.count = 0;
this.pointMesh.frustumCulled = false;
this.pointMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.scene.add(this.pointMesh);
this.glowMaterial = new THREE.ShaderMaterial({
uniforms: {
uColor: { value: this.accent.clone() },
uPixelRatio: { value: 1 }
},
vertexShader: `
uniform float uPixelRatio;
void main() {
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * mvPosition;
gl_PointSize = 15.0 * uPixelRatio;
}
`,
fragmentShader: `
uniform vec3 uColor;
void main() {
float distanceToCenter = length(gl_PointCoord - vec2(0.5));
float halo = smoothstep(0.5, 0.08, distanceToCenter);
float core = smoothstep(0.18, 0.0, distanceToCenter);
float alpha = halo * 0.12 + core * 0.3;
if (alpha < 0.01) discard;
gl_FragColor = vec4(uColor, alpha);
}
`,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending
});
this.glow = new THREE.Points(
new THREE.BufferGeometry(),
this.glowMaterial
);
this.glow.frustumCulled = false;
this.glow.renderOrder = 3;
this.scene.add(this.glow);
this.hoverRing = new THREE.Mesh(
new THREE.TorusGeometry(0.135, 0.012, 6, 28),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.88,
depthTest: false
})
);
this.hoverRing.visible = false;
this.hoverRing.renderOrder = 8;
this.scene.add(this.hoverRing);
this.raycaster = new THREE.Raycaster();
this.pointer = new THREE.Vector2();
this.dummy = new THREE.Object3D();
this.scratchColor = new THREE.Color();
this.lightColor = new THREE.Color(0xeafcff);
this.outlierColor = new THREE.Color(0xff4f70);
}
bindControls() {
this.canvas.addEventListener("pointerdown", (event) => {
this.dragging = true;
this.pointerId = event.pointerId;
this.lastPointer = { x: event.clientX, y: event.clientY };
this.stage.classList.add("is-dragging");
this.canvas.setPointerCapture(event.pointerId);
this.hideHover();
});
this.canvas.addEventListener("pointermove", (event) => {
if (this.dragging) {
const dx = event.clientX - this.lastPointer.x;
const dy = event.clientY - this.lastPointer.y;
this.targetTheta -= dx * 0.007;
this.targetPhi = THREE.MathUtils.clamp(
this.targetPhi + dy * 0.006,
-0.72,
0.72
);
this.lastPointer = { x: event.clientX, y: event.clientY };
} else {
this.updateHover(event);
}
});
const endDrag = (event) => {
this.dragging = false;
this.stage.classList.remove("is-dragging");
if (
this.pointerId !== null &&
this.canvas.hasPointerCapture(this.pointerId)
) {
this.canvas.releasePointerCapture(this.pointerId);
}
this.pointerId = null;
};
this.canvas.addEventListener("pointerup", endDrag);
this.canvas.addEventListener("pointercancel", endDrag);
this.canvas.addEventListener("pointerleave", () => {
if (!this.dragging) this.hideHover();
});
this.canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
this.targetRadius = THREE.MathUtils.clamp(
this.targetRadius * Math.exp(event.deltaY * 0.001),
8,
17
);
},
{ passive: false }
);
}
updateHover(event) {
if (!this.data.length) return;
const rect = this.canvas.getBoundingClientRect();
this.pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
this.pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
this.scene.updateMatrixWorld(true);
this.raycaster.setFromCamera(this.pointer, this.camera);
const hits = this.raycaster.intersectObject(
this.pointMesh,
false
);
if (!hits.length || !Number.isInteger(hits[0].instanceId)) {
this.hideHover();
return;
}
const index = hits[0].instanceId;
const point = this.data[index];
this.hoverRing.visible = true;
this.hoverRing.position.set(point.x, point.y, 0.14);
this.tooltip.hidden = false;
this.tooltip.innerHTML = `
<span>Observation ${String(index + 1).padStart(2, "0")}</span>
<b>x ${point.x.toFixed(2)} · y ${point.y.toFixed(2)}</b>
`;
const tooltipX = Math.min(
Math.max(8, event.clientX - rect.left + 13),
Math.max(8, rect.width - 155)
);
const tooltipY = Math.min(
Math.max(8, event.clientY - rect.top - 58),
Math.max(8, rect.height - 65)
);
this.tooltip.style.left = `${tooltipX}px`;
this.tooltip.style.top = `${tooltipY}px`;
}
hideHover() {
this.hoverRing.visible = false;
this.tooltip.hidden = true;
}
setData(data, correlation) {
this.data = data;
this.pointMesh.count = data.length;
for (let i = 0; i < data.length; i++) {
const point = data[i];
this.dummy.position.set(point.x, point.y, 0);
this.dummy.rotation.set(0, 0, 0);
this.dummy.scale.setScalar(point.outlier ? 1.28 : 1);
this.dummy.updateMatrix();
this.pointMesh.setMatrixAt(i, this.dummy.matrix);
if (point.outlier) {
this.scratchColor.copy(this.outlierColor);
} else {
const lightness = THREE.MathUtils.clamp(
(point.y + 2.1) / 4.2,
0,
1
);
this.scratchColor
.copy(this.accent)
.lerp(this.lightColor, lightness * 0.42);
}
this.pointMesh.setColorAt(i, this.scratchColor);
}
this.pointMesh.instanceMatrix.needsUpdate = true;
if (this.pointMesh.instanceColor) {
this.pointMesh.instanceColor.needsUpdate = true;
}
this.pointMesh.computeBoundingSphere();
const positions = new Float32Array(data.length * 3);
data.forEach((point, index) => {
positions[index * 3] = point.x;
positions[index * 3 + 1] = point.y;
positions[index * 3 + 2] = 0;
});
this.glow.geometry.dispose();
this.glow.geometry = new THREE.BufferGeometry();
this.glow.geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
this.fitLine.geometry.dispose();
this.fitLine.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-DOMAIN, -correlation * DOMAIN, 0.07),
new THREE.Vector3(DOMAIN, correlation * DOMAIN, 0.07)
]);
this.fitLine.computeLineDistances();
this.fitLine.visible = state.showFit;
}
resize() {
const width = Math.max(1, this.stage.clientWidth);
const height = Math.max(1, this.stage.clientHeight);
const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
this.renderer.setPixelRatio(pixelRatio);
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.glowMaterial.uniforms.uPixelRatio.value = pixelRatio;
}
resetView() {
this.targetTheta = -0.12;
this.targetPhi = 0.07;
this.targetRadius = 12;
}
update() {
this.theta += (this.targetTheta - this.theta) * 0.14;
this.phi += (this.targetPhi - this.phi) * 0.14;
this.radius += (this.targetRadius - this.radius) * 0.14;
const sinPhi = Math.sin(this.phi);
this.camera.position.set(
this.radius * sinPhi * Math.sin(this.theta),
this.radius * sinPhi * Math.cos(this.theta),
this.radius * Math.cos(this.phi)
);
this.camera.lookAt(0, 0, 0);
this.camera.updateMatrixWorld();
if (this.hoverRing.visible) {
this.hoverRing.lookAt(this.camera.position);
}
this.renderer.render(this.scene, this.camera);
}
}
function regenerate() {
const datasets = buildDatasets();
const statistics = [];
datasets.forEach((dataset, index) => {
const r = pearson(
dataset.map((point) => point.x),
dataset.map((point) => point.y)
);
const rho = spearman(
dataset.map((point) => point.x),
dataset.map((point) => point.y)
);
statistics.push({ r, rho, dataset });
plots[index].setData(dataset, state.r);
const card = $$(".plot-card")[index];
$("[data-role='r']", card).textContent = r.toFixed(2);
$("[data-role='rho']", card).textContent = rho.toFixed(2);
$("[data-role='gap']", card).textContent =
Math.abs(r - rho).toFixed(2);
$("[data-role='count']", card).textContent = dataset.length;
});
const rhos = statistics.map((stat) => stat.rho);
const outlierCount = statistics[3].dataset.filter(
(point) => point.outlier
).length;
$("#heroR").textContent = state.r.toFixed(2);
$("#insightR").textContent = `r = ${state.r.toFixed(2)}`;
$("#insightRho").textContent =
`${Math.min(...rhos).toFixed(2)}–${Math.max(...rhos).toFixed(2)}`;
$("#insightOutlier").textContent =
`${outlierCount} high-leverage observations`;
}
$("#sampleRange").addEventListener("input", (event) => {
state.n = Number(event.target.value);
$("#sampleOutput").textContent = state.n;
regenerate();
});
$("#corrRange").addEventListener("input", (event) => {
state.r = Number(event.target.value);
$("#corrOutput").textContent = state.r.toFixed(2);
regenerate();
});
$("#outlierRange").addEventListener("input", (event) => {
state.outlierStrength = Number(event.target.value);
$("#outlierOutput").textContent =
`${state.outlierStrength.toFixed(1)}×`;
regenerate();
});
$("#fitToggle").addEventListener("change", (event) => {
state.showFit = event.target.checked;
plots.forEach((plot) => {
plot.fitLine.visible = state.showFit;
});
});
$("#newSamples").addEventListener("click", () => {
state.seed = (state.seed + 7919) >>> 0;
regenerate();
});
$("#resetViews").addEventListener("click", () => {
plots.forEach((plot) => plot.resetView());
});
function animate() {
requestAnimationFrame(animate);
plots.forEach((plot) => plot.update());
}
const plots = stages.map((stage, index) => new ScatterPlot(stage, metadata[index].accent));
regenerate();
animate();
stages[0].scrollIntoView({ block: "center", behavior: "instant" });
</script>
</body>
</html>
```