Reputation: 4304
How would I set the depth between parent and child nodes for specified child nodes in a tree?
For example, the code below sets the depth between parent and child nodes for the whole tree:
nodes.forEach(function(d) {
d.y = (d.depth === 0 ? 50 : d.depth * 230);
});
So in the JSON example below, set the depth for d.name = "Son of Child 2"
, with the others at a default depth?
var treeData =
{
"name": "Top Level",
"children": [
{
"name": "Child 1",
"children": [
{ "name": "Son of Child 1" },
{ "name": "Daughter of Child 1" }
]
},
{ "name": "Child 2",
"children": [
{ "name": "Son of Child 2" },
{ "name": "Daughter of Child 2" }
] }
]
};
See fiddle
Upvotes: 2
Views: 711
Reputation: 38151
You just add the extra condition into your positioning function:
nodes.forEach(function(d){
if(d.data.name == "Child 1") d.y = d.depth*180+220;
else d.y = d.depth * 180
});
The above will add 220 px to the position that would be otherwise given for the node that has the given name.
We need to use d.data.name because the hierarchy places the original datum in a data property to avoid overlaps between hierarchical attributes and the original data.
Here's an updated fiddle.
One issue is that the children won't have positioning reflecting the parent's altered location, we can add an extra condition to see if a given node has the specified node as a parent:
nodes.forEach(function(d){
if(d.data.name == "Child 1") d.y = d.depth * 180 + 220;
else if(d.ancestors().some((a)=>a.data.name == "Child 1")) d.y = d.depth * 180 + 220;
else d.y = d.depth * 180
});
The only change being the condition to see if any of the ancestors (a
) of a give node (d
) have a given name.
This assumes only one parent will have the provided name, we could add additional logic to accommodate this circumstance. Here's a result from the above:
Upvotes: 1