11

Given a tree diagram like the Dendrogram example (source), how would one put labels on the edges? The JavaScript code to draw the edges looks like the next lines:

var link = vis.selectAll("path.link")
    .data(cluster.links(nodes))
  .enter().append("path")
    .attr("class", "link")
    .attr("d", diagonal);
TylerH
  • 20,799
  • 66
  • 75
  • 101
Will Ware
  • 475
  • 5
  • 17

1 Answers1

13

Mike Bostock, the author of D3, very graciously helped with the following solution. Define a style for g.link; I just copied the style for g.node. Then I replaced the "var link =...." code with the following. The x and y functions place the label in the center of the path.

var linkg = vis.selectAll("g.link")
    .data(cluster.links(nodes))
    .enter().append("g")
    .attr("class", "link");

linkg.append("path")
    .attr("class", "link")
    .attr("d", diagonal);

linkg.append("text")
    .attr("x", function(d) { return (d.source.y + d.target.y) / 2; })
    .attr("y", function(d) { return (d.source.x + d.target.x) / 2; })
    .attr("text-anchor", "middle")
    .text(function(d) {
        return "edgeLabel";
    });

The text function should ideally provide a label specifically for each edge. I populated an object with the names of my edges while preparing my data, so my text function looks like this:

    .text(function(d) {
        var key = d.source.name + ":" + d.target.name;
        return edgeNames[key];
    });
Will Ware
  • 475
  • 5
  • 17
  • A few people have been tempted to swap the x's and y's in the second and third lines of the `linkg.append("text")` piece. Please don't, they are correct as they are. There is an update because the [Dendrogram example](http://bl.ocks.org/mbostock/4063570) on the D3 website has changed. The first line should now read: `var linkg = svg.selectAll(".link")` – Will Ware Feb 03 '14 at 00:10