Demonstration for http://blog.infographics.tw/2015/05/d3js-tutorial-bubble-chart/
Last active
March 18, 2017 16:26
-
-
Save infographicstw/9d61356e9111f09ae16b to your computer and use it in GitHub Desktop.
D3.JS Pack Layout Tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
html, | |
body { | |
width: 100%; | |
height: 100%; | |
margin: 0; | |
padding: 0; | |
} | |
#root { | |
margin: 20px; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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