D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
veltman
Full window
Github gist
Mahalanobis distance
Calculating the
Mahalanobis distances
of a set of points.
<!DOCTYPE html> <meta charset="utf-8"> <body> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="mahalanobis.min.js"></script> <script> var margin = 25, width = 960 - 2 * margin, height = 500 - 2 * margin; var svg = d3.select("body").append("svg") .attr("width", width + 2 * margin) .attr("height", height + 2 * margin) .append("g") .attr("transform", "translate(" + margin + " " + margin + ")"); var x = d3.scaleLinear() .range([0, width]); var y = d3.scaleLinear() .range([height, 0]); d3.tsv("weight-height.tsv", arr, function(err, points){ x.domain(pad(d3.extent(points.map(function(d){ return d[0]; })), 0.02)); y.domain(pad(d3.extent(points.map(function(d){ return d[1]; })), 0.02)); var maxDistance = 0; mahalanobis(points).forEach(function(d, i){ if (d > maxDistance) maxDistance = d; points[i].push(d); }); var color = d3.scaleLinear() .domain([0, maxDistance]) .range([1, 0]); var unique = d3.map(points, function(d){ return d[0] + "-" + d[1]; }).values(); svg.selectAll("circle") .data(unique) .enter() .append("circle") .attr("r", 3) .attr("cx", function(d){ return x(d[0]); }) .attr("cy", function(d){ return y(d[1]); }) .attr("fill", function(d){ return d3.interpolateViridis(color(d[2])); }); svg.append("g") .attr("class", "axis x") .attr("transform", "translate(0 " + height + ")") .call(d3.axisBottom(x)); svg.append("g") .attr("class", "axis y") .call(d3.axisLeft(y)); }); function arr(row) { return [+row.weight, +row.height]; } function pad(extent, n) { var diff = n * (extent[1] - extent[0]); return [ extent[0] - diff, extent[1] + diff ]; } </script>
https://d3js.org/d3.v4.min.js