Skip to content

Instantly share code, notes, and snippets.

@infographicstw
Last active March 18, 2017 16:26
Show Gist options
  • Save infographicstw/9d61356e9111f09ae16b to your computer and use it in GitHub Desktop.
Save infographicstw/9d61356e9111f09ae16b to your computer and use it in GitHub Desktop.
D3.JS Pack Layout Tutorial
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#root {
margin: 20px;
}
<!DOCTYPE html><html lang="en"><head prefix="og: http://ogp.me/ns#"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>template</title><link rel="stylesheet" type="text/css" href="index.css"></head><body><div id="root"><svg width="100%" height="600px" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid"></svg></div><script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script><script type="text/javascript" src="index.js"></script></body></html>
d3.csv("population.csv", function(data) {
var dataobj = { children: data };
var pack = d3.layout.pack();
pack = pack.padding(2).size([800,600]).sort(function(a,b) { return b.value - a.value; });
var nodes = pack.nodes(dataobj);
nodes = nodes.filter(function(it) { return it.parent; });
var color = d3.scale.category20();
d3.select("svg")
.selectAll("circle") // 建立 circle 的 Selection
.data(nodes) // 綁定 selection 與資料
.enter() // 對於任何沒被對應而落單的資料 ...
.append("circle") // 新增一個 circle 標籤
.attr({
cx: function(it) { return it.x; }, // 用 x,y 當圓心
cy: function(it) { return it.y; },
r : function(it) { return it.r; }, // 用 r 當半徑
fill: function(it) { return color(it.country); },
stroke: "#444", // 邊框畫深灰色
});
d3.select("svg").selectAll("text").data(nodes).enter()
.append("text")
.attr({
x: function(it) { return it.x; },
y: function(it) { return it.y; },
"text-anchor": "middle", // 文字水平置中
}).text(function(it) { return (it.value>60000000?it.country:""); }); // 設定文字為國名
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment