【问题标题】:How to add text to Cluster Force Layout bubbles如何将文本添加到集群力布局气泡
【发布时间】:2016-09-08 04:15:47
【问题描述】:

我正在尝试将 JSON 文件中名称字段中的一些文本添加到集群中的每个气泡中。

https://plnkr.co/edit/hwxxG34Z2wYZ0bc51Hgu?p=preview

我已将我认为正确的属性添加到节点中

node.append("text")
    .text(function (d) {
    return d.name;
})
.attr("dx", -10)
.attr("dy", "5em")
.text(function (d) {
    return d.name
})
.style("stroke", "white");

    function tick(e) {
    node.each(cluster(10 * e.alpha * e.alpha))
    .each(collide(.5))
    .attr("transform", function (d) {
        var k = "translate(" + d.x + "," + d.y + ")";
    return k;
})

}

除标签外,一切正常。 我在这里错过了什么?

谢谢 凯夫

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    为此,您需要创建一个这样的组:

      var node = svg.selectAll("g")
        .data(nodes)
        .enter().append("g").call(force.drag);//add drag to the group
    

    向群组添加圈子。

    var circles = node.append("circle")
        .style("fill", function(d) {
          return color(d.cluster);
        })
    

    向组添加文本:

      node.append("text")
        .text(function(d) {
          return d.name;
        })
        .attr("dx", -10)
        .text(function(d) {
          return d.name
        })
        .style("stroke", "white");
    

    像这样将补间添加到组中的圆圈中:

      node.selectAll("circle").transition()
        .duration(750)
        .delay(function(d, i) {
          return i * 5;
        })
        .attrTween("r", function(d) {
          var i = d3.interpolate(0, d.radius);
          return function(t) {
            return d.radius = i(t);
          };
        });
    

    现在,tick 方法将平移组,并且随着组,圆圈和文本将占据其位置。

    工作代码here

    【讨论】:

    • 使用组的解决方案肯定更优雅。
    • 谢谢西里尔,这对我来说更有意义,但现在当你抓住一个圆圈并拖动它时,集群不会保持集群,其他人不会跟随,它不会重新集群。
    • 你制作集群的方式不正确我已经修复了它,这是拖拽失败的根本原因plnkr.co/edit/t6MsTWpWwI4VG1shqU2M?p=preview参考这个了解详细信息bl.ocks.org/mbostock/7882658
    【解决方案2】:

    问题:text SVG 元素不能是circle SVG 元素的子元素。

    解决方案是为文本创建另一个选择:

    var nodeText = svg.selectAll(".nodeText")
        .data(nodes)
        .enter().append("text")
        .text(function (d) {
            return d.name;
        })
        .attr("text-anchor", "middle")
        .style("stroke", "white")
        .call(force.drag);
    

    这里是 plunker:https://plnkr.co/edit/qnx7CQox0ge89zBL9jxc?p=preview

    【讨论】:

    • 感谢 Gerardo,我阅读了您发布的链接,特别是“了解 SVG 元素可以容纳哪些孩子”,这将我带到了w3.org/TR/SVG/struct.html,其中一些是我的,但大部分都是坚持。
    • 别担心,@Kevin。请考虑取消我的答案并将西里尔的答案标记为正确的答案,因为使用组是一种更优雅的解决方案(这是为未来的读者准备的)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    相关资源
    最近更新 更多