How to put labels on the edges in the Dendrogram example?

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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); 

回答1:

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];     }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!