D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Fil
Full window
Github gist
Weighted geoCentroid [UNLISTED]
Don't stay here, go see
this block
.
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin: 0; position: fixed; top: 0; right: 0; bottom: 0; left: 0; } </style> </head> <body> <script> function weightedCentroid(data){ let X0 = Y0 = Z0 = W0 = 0; const radians = Math.PI / 180; function centroidPoint(lambda, phi, w) { lambda *= radians, phi *= radians; var cosPhi = Math.cos(phi); centroidPointCartesian(cosPhi * Math.cos(lambda), cosPhi * Math.sin(lambda), Math.sin(phi), w); } function centroidPointCartesian(x, y, z, w) { W0 += +w; if (!w || !W0) return; w /= W0; X0 += (x - X0) * w; Y0 += (y - Y0) * w; Z0 += (z - Z0) * w; } data.map(d => centroidPoint(...d)); var x = X0, y = Y0, z = Z0, m = x * x + y * y + z * z; return [Math.atan2(y, x) / radians, Math.asin(z / Math.sqrt(m)) / radians]; } const width = 960, height = 500, margin = 40, scalepop = d3.scaleSqrt().domain([0, 100000]).range([0.2, 24]), scalecountry = d3.scaleOrdinal(d3.schemeCategory20b), projection = d3.geoEquirectangular(); d3.csv('cities.csv', function (cities) { const data = cities .sort((a, b) => d3.descending(+a[2015], +b[2015])) .map((d, i) => [+d.Longitude, +d.Latitude, +d[2015], +d['Country Code']]); const canvas = d3.select("body").append("canvas") .attr("width", width) .attr("height", height); const nodes = data.map(d => { let p = projection(d); d.x = p[0]; d.y = p[1]; d.r = scalepop(d[2]); d.color = '#bbb'; return d; }); draw(canvas, nodes); // draw the unweighted geoCentroid setTimeout(function() { const centroid = d3.geoCentroid({ type: "MultiPoint", coordinates: data.map(d => [d[0], d[1]]) }); let p = projection(centroid); draw(canvas, [{ x: p[0], y: p[1], r: 6, color: '#8e84ff', stroke: 'black', }]); }, 500); // draw the *weighted* geoCentroid setTimeout(function() { const wcentroid = weightedCentroid(data.map(d => [d[0], d[1], d[2]])); let p = projection(wcentroid); draw(canvas, [{ x: p[0], y: p[1], r: 12, color: '#ff8684', stroke: 'black', }]); }, 1000); function draw(canvas, nodes) { let context = canvas.node().getContext("2d"); for (var i = 0, n = nodes.length; i < n; ++i) { var node = nodes[i]; context.beginPath(); context.moveTo(node.x, node.y); context.arc(node.x, node.y, node.r, 0, 2 * Math.PI); context.lineWidth = 8; if (node.stroke){ context.color = node.stroke; context.stroke(); } context.fillStyle = node.color; context.fill(); } } }); </script> </body>
https://d3js.org/d3.v4.min.js