D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
63anp3ca
Full window
Github gist
Bubble Chart GDP by Country
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> ; var height = 500; function transformToGenericObjectList(flatData) { var container = {}; container.children = []; var regionToCountry = {}; flatData.forEach(entry => { if (entry["2016"] !== "") { container.children.push({group: entry["Region"], value: parseFloat(entry["2016"]), name: entry["Country Name"]}); } }); return container; } function chart(root) { const svg = d3.select(DOM.svg(width, height)); var format = d3.format(",d"), color = d3.scaleOrdinal(d3.schemeSet3) var tooltip = d3.select("body").append("div") .style("position", "absolute") .style("z-index", "10") .style("visibility", "hidden") .style("color", "white") .style("padding", "8px") .style("background-color", "rgba(0, 0, 0, 0.75)") .style("border-radius", "6px") .style("font", "12px sans-serif") .text("tooltip"); var bubble = d3.pack() .size([width, height]) .padding(1.5); bubble(root); var node = svg.selectAll(".node") .data(root.children) .enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); node.append("circle") .attr("r", function(d) { return d.r; }) .style("fill", function(d) { return color(d.data.group); }) .on("mouseover", function(d) { tooltip.text(d.data.name + ": " + format(d.value)); tooltip.style("visibility", "visible"); d3.select(this).style("stroke", "black"); }) .on("mousemove", function() { return tooltip.style("top", (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px"); }) .on("mouseout", function() { d3.select(this).style("stroke", "none"); return tooltip.style("visibility", "hidden"); }); node.append("text") .attr("dy", ".3em") .style("text-anchor", "middle") .style("font", "10px sans-serif") .style("pointer-events", "none") .text(function(d) { return d.data.name.substring(0, d.r / 3); }); return svg.node(); } function doScatterPlot(myData, svg) { console.log("w", width, "h", height); } // Returns a promise, you don't get the data straight from it d3.csv("https://gist.githubusercontent.com/mmattozzi/60e2427a5af24360388fabe4de213427/raw/4d6a1842424c6b265764c7a7bb8682822be04ee6/gdp-by-country-worldbank.csv") .then( data => { //doScatterPlot(data, d3.select("#viz")); // doScatterPlot(data, d3.select("#viz2")); d3.hierarchy(transformToGenericObjectList(data)) .sum(function(d) { return d.value; }) .sort(function(a, b) { a.group < b.group ? -1 : 1 }) chart(d3.hierarchy(transformToGenericObjectList(data)) .sum(function(d) { return d.value; }) .sort(function(a, b) { return b.value - a.value })) }); </script> </body>
https://d3js.org/d3.v5.min.js