I have a static force node visual that looks like this:
And relevant code:
const node2 = g.append("g")
.selectAll(".labels")
.data(nodes)
.join("text")
.attr('x', d=> d.x)
.attr('y', d=> d.y+3)
.attr('text-anchor','middle')
.attr('class','labels')
//.text(d=> d.data.name)
.text(function(d,i) {return i-2})
.style("fill", d=> d.children ? "none": d.data.new==true?"#fff":"#000")
.style('font-size',12);
Data looks like:
{"name":"Name1", tree: {
"name":"center",
"children": [
{"name":"category1","children":[{"name":"node1"},{"name":"node2"},{"name":"node3"}]},
{"name":"category2","children":[{"name":"node4"},{"name":"node5"}]},
]
}
}
What I would like to have here is for the labels to display a count sort of "id" for each node starting from 1. I initially thought I could subtract off 2 like: i-2. However for simpler force structures this resulted in too much, leaving the count starting at 0.
How can I make my count logic robust to display a count that includes only children (regardless of parent/overall structure)
Edit
I've also tried to apply a parent count logic, but this gave me all NaNs:
.text(function(d,i) {
if (d.depth==0) {
console.log(d)
var parents = d.children.length;
}
return i-parents;
//return i-2
})
Edit 2 I got it working by changing parents to a global but it seems a bit hacky. Still would welcome a more sophisticated answer.