version
d3.jsのversionは4.1.0です。
ビジュアライズ結果
Data
地下鉄の駅データをサンプルとして使います。
data.json
{
"name": "都営地下鉄",
"parent": "null",
"children": [
{
"name": "大江戸線",
"parent": "都営地下鉄",
"children": [
{
"name": "青山一丁目",
"parent": "大江戸線"
},
{
"name": "六本木",
"parent": "大江戸線"
}
]
},
{
"name": "浅草線",
"parent": "都営地下鉄"
}
]
}
Code
js
本記事ではコードを一部抜粋して掲載しています。詳細は全コードをご覧ください。
SVGを作成
Visualization.js
d3.select('body').append('svg')
.attr('width', this.width)
.attr('height', this.height)
.append("g")
.attr("transform", "translate(" + this.margin.left + "," + (this.margin.top) + ")");
Treeを作成
Visualization.js
this.margin = {top: 50, right: 0, bottom: 0, left: 200};
this.width = window.innerWidth - this.margin.left - this.margin.right,
this.height = window.innerHeight - this.margin.top - this.margin.bottom;
this.tree = d3.tree()
.size([this.height, this.width - 400]);
jsonを読み込む
Visualization.js
d3.json("datasets/data.json", (error, data) => {
this.root = d3.hierarchy(data);
this.tree(this.root);
});
hierarchy関数を使います。
d3/d3-hierarchy: 2D layout algorithms for visualizing hierarchical data.
線で繋ぐ
Visualization.js
this.svg.selectAll(".link")
.data(this.root.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.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;
});
Nodeを作成
Visualization.js
this.svg.selectAll(".node")
.data(this.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 + ")"; });
円を表示
Visualization.js
this.node.append("circle")
.attr("r", 2.5);
駅名を表示
textを追加します。
Visualization.js
this.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; });