Search code examples
javascriptd3.js

D3 dendrogram straight edges


Looking through the documentation on d3.cluster() I did not see anything that the developer can use to set the type of connecting line. It seems that there is only a curved spline kind of connection, but this is not the most conventional styling for dendrograms -- at least for my situation. What I'm after is a vertically oriented, 90 degree angle joined nodes:

enter image description here

Question

Judging by the documentation, there is no direct built-in solution, but is there anything that d3.cluster() can offer to achieve the above result? Or am I better off coding everything from scratch?


Solution

  • This issue has been asked before in "d3js Tree square". However, I do not really consider this a duplicate as that old question was using D3 v3 and, as it turns out, is not easily adapted to v5. Furthermore, you are explicitly asking for a vertical layout.

    Nonetheless, the basic approach stays the same: just use a custom path generator. Building upon the old v3 Block this could be done as follows:

    svg.selectAll(".link")
      .data(root.links())
      .enter().append("path")
        .attr("d", elbow);   // Appended paths use the custom path generator.
    
    // Custom path generator    
    function elbow(d) {
      return "M" + d.source.x + "," + d.source.y + "H" + d.target.x + "V" + d.target.y;
    }
    

    With some minor modifications to work with the v5 API Mike Bostock's demo can be rewritten as a Vertical "Elbow" Dendrogram.

    Note, that this is the same approach Mike Bostock used in his Tree of Life notebook where he used multiple custom path generators to create radial layouts.