DAY 27
0
Data Technology

## D3 tree

### 樹狀圖

``````var datapath='https://raw.githubusercontent.com/FWcloud916/TWcity/master/city.json';
d3.json(datapath,function(d){
var root = d3.hierarchy(dataset);
``````

size:樹的高度、寬度
separation:節點的間隔

``````  var tree = d3.tree()
.size([height, width])
.separation(function(a, b) {
return (a.parent == b.parent ? 1 : 2);
});

tree(root); //將資料放進去
``````

descendants是用來回傳節點所接的資料數目，slice是用來去掉不需要的，根節點(台灣)是樹根沒有連到它的線，所以利用slice來刪去

``````  var link = svg.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
.attr("d", function(d) {
return "M" + d.y + "," + d.x
+ "C" + (d.y + d.parent.y) / 2 + "," + d.x
+ " " + (d.y + d.parent.y) / 2 + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});

var node = svg.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", function(d) {
return "node" + (d.children ? " node--internal" : " node--leaf");
})
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});

node.append("circle")
.attr("r", 5);

node.append("text")
.attr("dy", 3)
.attr("x", function(d) {
return d.children ? -8 : 8;
})
.style("text-anchor", function(d) {
return d.children ? "end" : "start";  //判斷是葉節點或是根結點，來決定文字在前或後
})
.text(function(d) {
return d.data.name;
});

});
``````

## demo & code : https://codepen.io/FanWay/pen/vpzYpV 參考:https://bl.ocks.org/mbostock/433918

``````d3.json(datapath,function(d){
var dataset = d;
var tree = d3.tree()
.size([2 * Math.PI, 600])
.separation(function(a, b) {
return (a.parent == b.parent ? 1: 2)/a.depth;
});

var root = d3.hierarchy(dataset);
``````

``````	tree(root);
.enter().append("path")
.angle(function(d) {
return d.x;
})
return d.y;
})
);
``````

``````function radialPoint(x, y) {
return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)];
}
``````

``````	var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", function(d) {
return "node" + (d.children ? " node--internal" : " node--leaf");
})
.attr("transform", function(d) {
return "translate(" + radialPoint(d.x, d.y) + ")";
});

node.append("circle")
.attr("r",3);

node.append("text")
.attr("dy", "0.31em")
.attr("x", function(d) {
return d.x < Math.PI === !d.children ? 6 : -6;
})
.attr("text-anchor", function(d) {
return d.x < Math.PI === !d.children ? "start" : "end";
})
.attr("transform", function(d) {
return "rotate(" + (d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180 / Math.PI + ")";
})
.text(function(d) {
return d.data.name;
});

})
``````