Skip to content

Instantly share code, notes, and snippets.

@daneden

daneden/.block

Forked from mbostock/.block
Last active Aug 3, 2017
Embed
What would you like to do?
Circle Packing
license: gpl-3.0
height: 960
border: no

Circle-packing representing the 50 most populous countries in the world.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
circle {
fill: transparent;
fill-opacity: .25;
stroke: #fff;
stroke-width: 1px;
}
.leaf circle {
fill: #000;
fill-opacity: 1;
}
text {
fill: #fff;
font: 10px "Input Mono Compressed";
text-anchor: middle;
}
</style>
<svg width="2600" height="2600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
diameter = +svg.attr("width"),
g = svg.append("g").attr("transform", "translate(2,2)"),
format = d3.format(",d");
var pack = d3.pack()
.size([diameter - 4, diameter - 4]);
d3.csv("worldPops.csv", function(error, data) {
if (error) throw error;
var root = {name: "countries", children: data}
root = d3.hierarchy(root)
.sum(function(d) { return d.population; })
.sort(function(a, b) { return b.value - a.value; });
var node = g.selectAll(".node")
.data(pack(root).descendants())
.enter().append("g")
.attr("class", function(d) { return d.children ? "node" : "leaf node"; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return d.data.country + "\n" + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; });
node.filter(function(d) { return !d.children; }).append("text")
.attr("dy", "0.3em")
.text(function(d) { console.log(d); return d.data.country; });
});
</script>
country population
China 1373541278
India 1266883598
United States 323995528
Indonesia 258316051
Brazil 205823665
Pakistan 201995540
Nigeria 186053386
Bangladesh 156186882
Russia 142355415
Japan 126702133
Mexico 123166749
Philippines 102624209
Ethiopia 102374044
Vietnam 95261021
Egypt 94666993
Iran 82801633
Congo 81331050
Germany 80722792
Turkey 80274604
Thailand 68200824
France 66836154
United Kingdom 64430428
Italy 62007540
Burma 56890418
South Africa 54300704
Tanzania 52482726
South Korea 50924172
Spain 48563476
Colombia 47220856
Kenya 46790758
Ukraine 44209733
Argentina 43886748
Algeria 40263711
Poland 38523261
Uganda 38319241
Iraq 38146025
Sudan 36729501
Canada 35362905
Morocco 33655786
Afghanistan 33332025
Malaysia 30949962
Venezuela 30912302
Peru 30741062
Uzbekistan 29473614
Nepal 29033914
Saudi Arabia 28160273
Yemen 27392779
Ghana 26908262
Mozambique 25930150
North Korea 25115311
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment