i have a question about d3.js I have this basic example running: https://i.sstatic.net/8nMD1.png and a basic json format:
{
"name": "root",
"children": [
{
"name": "parent A",
"children": [
{"name": "child A1"},
{"name": "child A2"},
{"name": "child A3"}
]
},{
"name": "parent B",
"children": [
{"name": "child B1"},
{"name": "child B2"}
]
}
]
}
My javascript code is here:
<!doctype html></html>
<meta charset="utf-8" />
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 20px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var width = 600;
var height = 500;
var cluster = d3.layout.cluster()
.size([height, width-200]);
var diagonal = d3.svg.diagonal()
.projection (function(d) { return [d.y, d.x];});
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height)
.append("g")
.attr("transform","translate(100,0)");
d3.json("dendrogram03.json", function(error, root){
var nodes = cluster.nodes(root);
var links = cluster.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class","link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class","node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dx", function(d) { return d.children ? -8 : 8; })
.attr("dy", 3)
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text( function(d){ return d.name;});
});
</script>
But the problem is that i looked for d3 documentation but is not so good, so i want to put every node in a different height of the tree like this way: https://i.sstatic.net/49a6v.png
To accomplish this you could descend the tree with a recursive function and modify the y attribute on each child, incriminating the amount of modification each time you loop through the set of child nodes.
You will need some modifying function after the creation of the nodes but before the creation of the links:
var nodes = cluster.nodes(root).reverse();
create_offset(nodes[0]);
var links = cluster.links(nodes);
the function for creating the offset could look something like this:
function create_offset(node){
if(node.children){
//modify the y values of each child. increasing the offset each time
var offset = 0;
for(var i = 0; i<node.children.length;i++){
node.children[i].y = node.children[i].depth * 100 + offset;
offset += 20; //change this to change the degree of offset
}
//check each child to see if it has it's own children. If so, decend the tree recursively
for(var i = 0; i<node.children.length;i++){
if(node.children[i].children){
create_offset(node.children[i]);
}
}
}
}
Note: be sure nodes[0]
in create_offset(nodes[0]);
is the root node. I'm fairly sure it will be but you should double check