如何在树状图示例中将标签放在边缘?

How to put labels on the edges in the Dendrogram example?(如何在树状图示例中将标签放在边缘?)

本文介绍了如何在树状图示例中将标签放在边缘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类似于 Dendrogram 示例的树形图(source),如何将标签放在边缘?绘制边缘的 JavaScript 代码如下所示:

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

推荐答案

D3 的作者 Mike Bostock 非常慷慨地帮助了以下解决方案.为 g.link 定义一个样式;我刚刚复制了 g.node 的样式.然后我用以下代码替换了var link =...."代码.x 和 y 函数将标签放置在路径的中心.

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

这篇关于如何在树状图示例中将标签放在边缘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在树状图示例中将标签放在边缘?

基础教程推荐