Reputation: 314
How can I position the nodes of a d3 tree chart with variable dimensions?
here is what I have so far, as you can see the positioning is way off
http://jsfiddle.net/cdad0jyz/1/
I have tried to use the separation method:
var tree = d3.layout.tree()
.nodeSize([10,10])
.separation(function(a, b) {
var width = 200, // here should be a value calculated for each node
distance = width / 2 + 16;
return distance;
});
Upvotes: 1
Views: 2524
Reputation: 108512
In your code, you set x
and y
on your text
elements but not on the corresponding rects
. To further complicate it, each rect has a random width and height making it difficult to center it on the text.
This is one way to solve it:
nodeEnter.append("rect")
.attr("width", genRand) //rectW
.attr("height", genRand) // rectH
.attr("x", function(){
return (rectW / 2) - (d3.select(this).attr('width') / 2);
})
.attr("y", function(){
return (rectH / 2) - (d3.select(this).attr('height') / 2);
})
.attr("stroke", "black")
.attr("stroke-width", 1)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
Updated fiddle.
Upvotes: 2