D3 Tree from Data Frame
HTML
<script src="//d3js.org/d3.v3.min.js"></script>
CSS
svg path{
fill: none;
}
circle.node {
opacity: 0.8;
}
JavaScript
links = [
{source: 'A1', target: 'A2', color: "green"},
{source: 'A2', target: 'A3', color: "red"},
{source: 'A2', target: 'A4', color: "blue"},
{source: 'A4', target: 'A5', color: "steelblue"},
{source: 'A4', target: 'A6', color: "darkred"}
]
var nodeProps = {
"A1" : {a: 1, b: 2, color: 'red'},
"A2" : {a: 2, b: 4, color: 'green'},
"A3" : {a: 2, b: 4, color: 'blue'},
"A4" : {a: 2, b: 4, color: 'maroon'},
"A5" : {color: "steelblue"},
"A6" : {color: "orange"}
}
makeTreeData = function(links){
var nodesByName = {};
// Create nodes for each unique source and target.
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];
});
function nodeByName(name) {
return nodesByName[name] || (nodesByName[name] = {name: name});
}
return(links)
}
links = makeTreeData(links)
function separation(a, b) {
return a.parent == b.parent ? 1 : 1.6;
}
var margin = {top: 40, right: 40, bottom: 40, left: 40},
width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var tree = d3.layout.tree()
.size([width, height])
.separation(separation)
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.x, d.y]; });
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 root = links[2].source
//root.x0 = height / 2;
//root.y0 = 0;
// Extract the root node and compute the layout.
var nodes = tree.nodes(root);
// Create the link lines.
svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal)
.attr("stroke", function(d){return d.color})
//...