JSFiddle - React, Tailwind, and code Playground
by chrisJamesC
HTML
<pre id="graph_csv">
source,target
1,2
1,3
1,4
2,5
2,6
11,22
14,21
3,7
3,8
4,9
4,10
5,11
5,12
5,13
6,14
6,15
7,16
8,17
9,18
10,19
10,20
</pre>
<pre id="nodes_csv">
node_id,node_name
1,Node1
2,Node2
3,Node3
4,Node4
5,Node5
6,Node6
7,Node7
8,Node8
9,Node9
10,Node10
11,Node11
12,Node12
13,Node13
14,Node14
15,Node15
16,Node16
17,Node17
18,Node18
19,Node19
20,Node20
21,Node21
22,Node22
</pre>
CSS
#graph_csv, #nodes_csv {
display: none;
}
JavaScript
var margin = {top: 40, right: 40, bottom: 40, left: 40}, width = 1024 - margin.left - margin.right, height = 768 - margin.top - margin.bottom;
var tree = d3.layout.tree()
.size([height, width]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var links = d3.csv.parse(d3.select("#graph_csv").text());
var nodesByName = {};
links.forEach(function(link) {
var parent = link.source = nodeByName(link.source),
child = link.target = nodeByName(link.target);
if (parent.children) parent.children.push(child);
else parent.children = [child];
});
var nodes = tree.nodes(links[0].source);
svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.y; })
.attr("y1", function(d) { return d.source.x; })
.attr("x2", function(d) { return d.target.y; })
.attr("y2", function(d) { return d.target.x; });
svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.attr("cx", function(d) { return d.y; })
.attr("cy", function(d) { return d.x; });
var names = d3.csv.parse(d3.select("#nodes_csv").text());
var namesMap = {};
names.forEach(function(d) {
namesMap[d.node_id] = d.node_name;
});
svg.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("class", "label")
.attr("x",function(d) { return (d.y - 25); })
.attr("y",function(d) { return (d.x + 20); })
.text(function(d){ return namesMap[d.name]; });
function nodeByName(name) {
return nodesByName[name] ||...