score:3

Accepted answer

your logic for determining the node's name to be used for getting the color from the scale is flawed:

(d.children ? d : d.parent).name

which translates to:

if i've got children then use my name, and if i've got no children then use my parent's name instead.

this, however, is not what you want. you are looking for

give me the name of my ancestor which is closest to the root without being the root itself.

there are various ways to implement this logic:

1. by recursion

to my eye this is the most elegant way to achieve what you are after.

function getrootmostancestorbyrecursion(node) {
    return node.depth > 1 ? getrootmostancestorbyrecursion(node.parent) : node;
}

2. by iteration

you may also apply various kinds of iterations using all sorts of loops known to javascript.

function getrootmostancestorbywhileloop(node) {
    while (node.depth > 1) node = node.parent;
    return node;
}

the call to either of these functions will then replace the above mentioned erroneous statement.

.style("fill", function (d) { return colors(getrootmostancestorbyrecursion(d).name); })

depending on your amount of data and on how often this logic will get called, you might want to consider doing this once for your entire tree and store the rootmost parent's name on every node.


Related Query

More Query from same tag