d3.js - 如何向 d3.js 力气泡图添加标签

标签 d3.js force-layout bubble-chart word-cloud

我正在尝试修改此代码bl.ocks.org/mbostock/7881887,以便我可以使用该技术来显示文字云,其中圆圈大小将相对于文件中的单词数,但我的主要目前的问题是首先要找出如何将文本添加到圆圈中。令人着迷的是,我可以看到代码中执行此操作的函数......node.append(“text”)?所以我假设我能够在节点函数中向“d”添加一个“name”值,然后我们就可以走了。正如你所看到的,我刚刚添加了 name: text where text = "Test"到 d. 任何让任何文本出现在这些圆圈内或附近的帮助将非常感激!正如你可能知道的那样,我是新的 D3,并且花了很多个晚上在谷歌上搜索这个内容,但什么也没找到。我可以在不同类型的图表上看到示例...力布局例如 http://bl.ocks.org/mbostock/1093130但它们看起来如此不同,我无法将其中一个应用到另一个:-(

这是我的 jsfiddle https://jsfiddle.net/TimBrighton/vn7reroe/1/

var width = 960,
    height = 500,
    padding = 1.5, // separation between same-color nodes
    clusterPadding = 6, // separation between different-color nodes
    maxRadius = 12;

var n = 100, // total number of nodes
    m = 5; // number of distinct clusters

var color = d3.scale.category10()
    .domain(d3.range(m));

// The largest node for each cluster.
var clusters = new Array(m);

var nodes = d3.range(n).map(function() {
  test="Test";
  var i = Math.floor(Math.random() * m),
      r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius,      
      d = {
        name: test,
        cluster: i,
        radius: r,
        name: "test",
        x: Math.cos(i / m * 2 * Math.PI) * 200 + width / 2 + Math.random(),
        y: Math.sin(i / m * 2 * Math.PI) * 200 + height / 2 + Math.random()
      };
  if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
  console.log(d.name);
  return d;

});

var force = d3.layout.force()
    .nodes(nodes)
    .size([width, height])
    .gravity(.02)
    .charge(0)
    .on("tick", tick)
    .start();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var node = svg.selectAll("circle")
    .data(nodes)
  .enter().append("circle")
    .style("fill", function(d) { return color(d.cluster); })
    .call(force.drag);


node.append("text")
.text(function(d) { return d.name; })
     // .style("font-size", function(d) { return Math.min(2 * d.r, (2 * d.r - 8) / this.getComputedTextLength() * 24) + "px"; })
     //.attr("dy", ".35em");

    .attr("dx", 10)
    .attr("dy", ".35em")
    .text(function(d) { return d.name })
    .style("stroke", "gray");

node.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); };
    });




function tick(e) {
  node
      .each(cluster(10 * e.alpha * e.alpha))
      .each(collide(.5))
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

// Move d to be adjacent to the cluster node.
function cluster(alpha) {
  return function(d) {
    var cluster = clusters[d.cluster];
    if (cluster === d) return;
    var x = d.x - cluster.x,
        y = d.y - cluster.y,
        l = Math.sqrt(x * x + y * y),
        r = d.radius + cluster.radius;
    if (l != r) {
      l = (l - r) / l * alpha;
      d.x -= x *= l;
      d.y -= y *= l;
      cluster.x += x;
      cluster.y += y;
    }
  };
}

// Resolves collisions between d and all other circles.
function collide(alpha) {
  var quadtree = d3.geom.quadtree(nodes);
  return function(d) {
    var r = d.radius + maxRadius + Math.max(padding, clusterPadding),
        nx1 = d.x - r,
        nx2 = d.x + r,
        ny1 = d.y - r,
        ny2 = d.y + r;
    quadtree.visit(function(quad, x1, y1, x2, y2) {
      if (quad.point && (quad.point !== d)) {
        var x = d.x - quad.point.x,
            y = d.y - quad.point.y,
            l = Math.sqrt(x * x + y * y),
            r = d.radius + quad.point.radius + (d.cluster === quad.point.cluster ? padding : clusterPadding);
        if (l < r) {
          l = (l - r) / l * alpha;
          d.x -= x *= l;
          d.y -= y *= l;
          quad.point.x += x;
          quad.point.y += y;
        }
      }
      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    });
  };
}

最佳答案

您正在将 TEXT DOM 添加到圆形 DOM 中。

这就是您看不到文本的原因。

<circle cx="331.0297405069362" cy="238.4899367858363" style="fill: rgb(255, 127, 14);" r="24.842603758681765">
    <text dx="10" dy=".35em" style="stroke: gray;">test</text>
</circle>

这是不正确的。

正确的方法是让一个组添加圆圈和文本。 像这样:

<g transform="translate(402.3818560847106,240.01473655622326)">
   <circle r="31.769893912794977" style="fill: rgb(255, 127, 14);">   </circle>
   <text dx="-10" dy=".35em" style="stroke: gray;">test</text>
</g>

因此,首先要创建这样的组:

var node = svg.selectAll("circle")
    .data(nodes)
    .enter().append("g").call(force.drag);

将圈子添加到组中:

node.append("circle")
    .style("fill", function (d) {
    return color(d.cluster);
}).attr("r", function(d){return d.radius})

向组中添加文本

//add text to the group    
node.append("text")
    .text(function (d) {
    return d.name;
})
.attr("dx", -10)
    .attr("dy", ".35em")
    .text(function (d) {
    return d.name
})
    .style("stroke", "gray");

在tick函数内,我们需要移动整个组,而不是更新圆的cx cy,因此请使用像thsi这样的变换:

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

}

工作代码here .

关于d3.js - 如何向 d3.js 力气泡图添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928409/

相关文章:

javascript - 如何根据列值给DC js气泡图着色?

javascript - 将 `enter` selectin 合并到 `update` selections

javascript - D3.js错误: Invalid value for <path> attribute for a line chart

javascript - 如何在 D3 Force 布局中组织节点位置

r - 如何从 R bubbleGoogleMaps 获取比例气泡大小?

r - 向 R 气泡图添加基于颜色的区分

javascript - 如何隐藏条形图轴的线条?

javascript - d3.js 强制布局具有一些固定节点(在网格中)

d3.js - 基础数据更改时如何更新D3元素的布局

R 绘制如何将文本链接到气泡以便在单击图例时将其删除