【问题标题】:Add text label to d3 node in Force directed Graph and resize on hover在 Force 有向图中将文本标签添加到 d3 节点并在悬停时调整大小
【发布时间】:2013-08-12 10:06:21
【问题描述】:

我正在尝试向 d3 Force Directed Graph 中的节点添加文本标签,似乎存在问题。 这是我的Fiddle:

当我像这样添加节点名称时:

node.append("text")
    .attr("class", "word")
    .attr("dy", ".35em")
    .text(function(d) {
        console.log(d.name);
        return d.name;
    });

没有变化,但名称正在被记录。

当我尝试使用 bounding box 时,出现了节点标签,但节点堆叠在框的左上角,而节点链接很好。这个 fiddle 是我付出的努力的结果。谁能告诉我我做错了什么?

【问题讨论】:

    标签: javascript svg d3.js label force-layout


    【解决方案1】:

    您在一个圆圈内添加一个文本元素,这是行不通的。您可以在 svg 元素下添加组,然后在每个组中附加圆圈和文本:

    // Create the groups under svg
    var gnodes = svg.selectAll('g.gnode')
      .data(graph.nodes)
      .enter()
      .append('g')
      .classed('gnode', true);
    
    // Add one circle in each group
    var node = gnodes.append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);
    
    // Append the labels to each group
    var labels = gnodes.append("text")
      .text(function(d) { return d.name; });
    
    force.on("tick", function() {
      // Update the links
      link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });
    
      // Translate the groups
      gnodes.attr("transform", function(d) { 
        return 'translate(' + [d.x, d.y] + ')'; 
      });    
    
    });
    

    这个策略的一个分支是here

    【讨论】:

    • 几乎是我想要的,必须在悬停时重新调整大小。非常感谢。
    • 我知道这篇文章很旧,但请注意 .call(force.drag) 应该在 gnodes 上,而不是在节点上。
    • 在gnodes 上使用call(force.drag) 将允许用户拖动标签或圆圈(组下的所有内容),而在node 中使用它们只允许拖动圆圈。跨度>
    • 我应该把 exit().remove() 调用放在哪里?您需要拥有它才能更新图表
    • 在force.on('tick', callback) 调用之前或之后,可能在原始小提琴jsfiddle.net/draditya91/RRUzZ 的drawGraph 函数中
    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 2017-01-04
    • 2018-09-04
    • 2013-08-08
    • 2012-11-02
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多