d3-hierarchy icon indicating copy to clipboard operation
d3-hierarchy copied to clipboard

Stratify nodes that are both a leaf (with value) and a parent

Open Fil opened this issue 2 years ago • 0 comments

I wonder if it should not be an option of stratify (or even the default, if the current behavior is considered a bug), to create a leaf node to represent the data of a node that has children.

with the typical value:

/gallery,4
/gallery/chart-a,2
/gallery/chart-b,1

currently stratify builds a tree with three nodes and the values:

  • /gallery 4
    • /gallery/chart-a 2
    • /gallery/chart-b 1

and a treemap representation (for example) doesn't see the value of 4 that pertains to the /gallery node.

With the following function, we would introduce a child node /gallery/ with that value:

  • /gallery null
    • /gallery/ 4
    • /gallery/chart-a 2
    • /gallery/chart-b 1
stratify = (data, path) => (d3.stratify().path(path)(data)).each(node => {
    if (node.children?.length && node.data != null) {
      const child = new d3.Node(node.data);
      node.data = null;
      child.depth = node.depth + 1;
      child.height = 0;
      child.parent = node;
      child.id = node.id + "/";
      node.children.unshift(child);
    }
  });

see https://observablehq.com/@d3/treemap-parent-with-value-206

Fil avatar Jul 19 '23 07:07 Fil