Public
Edited
May 21, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
// normal random number generator using a seed
const rnorm = d3.randomNormal.source(d3.randomLcg(2));
// scale a set of numbers to be within the range [0, 1]
const unitify = (a) => { let lo=d3.min(a); let hi=d3.max(a); return a.map( (x) => (x - lo)/(hi - lo) ); }
// scale a set of numbers to have an SD of 1
// Cleveland, Diaconis, McGill. Science (1982)
// Suggested by Jeremy Wilmer
const scale_sd = (a) => { let avg=d3.mean(a); let sd=d3.deviation(a); return a.map(b => (b-avg)/sd); }
// which scale to use
const scale_function = (scale_by == "Unit") ? unitify : scale_sd;

// generate x and y as normal distributions
var x = (Array.from({length: 200}, rnorm(0)));
var y = (x.map((a) => rnorm(multiple * a, 1)()));
// get the ranks (integer order) of the numbers
const rank_x = scale_function(d3.rank(x));
const rank_y = scale_function(d3.rank(y));
// scale x and y from 0 to 1
x = scale_function(x);
y = scale_function(y);
// convert to indexable datums
let data = [];
for (let i = 0; i < x.length; ++i) {
data[i] = {x:x[i], y:y[i], rank_x:rank_x[i], rank_y:rank_y[i]};
}
// get the regression info (from Correll's code)
const fit_original = vega.regressionLinear(data, d=>d.x, d=>d.y);
const fit_rank = vega.regressionLinear(data, d=>d.rank_x, d=>d.rank_y);
const r_original = Math.sqrt(fit_original.rSquared);
const r_rank = Math.sqrt(fit_rank.rSquared);
d3.select("#original_r").text( d3.format(".2f")(r_original) );
d3.select("#ranked_r").text( d3.format(".2f")(r_rank) );
// plot it
return Plot.plot({
aspectRatio: 1,
height: 600,
inset: 30,
nice: true,
marks: [
Plot.frame(),
Plot.dot(data, rank ? {x:rank_x, y:rank_y, fill:"red"} : {x:x, y:y, fill:"blue"}),
Plot.arrow(data, {x1:x, y1:y, x2:rank_x, y2:rank_y, opacity:arrows ? 0.5 : 0, fill: "black", stroke: "black"}),
Plot.linearRegressionY(data, rank?
{x:x, y:y, stroke:"red", opacity:linear_fit?1:0} :
{x:rank_x, y:rank_y, stroke:"blue", opacity:linear_fit?1:0})
]
});
}
Insert cell
viewof avg_vector = [0,0];
Insert cell
vega = import("https://cdn.skypack.dev/vega-statistics")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more