javascript - D3 JavaScript 网络 : How to parametrize node size with the number of links?

标签 javascript d3.js

我想用 d3.js 创建一个网络。我创建了一个,如下所示,但我希望节点大小取决于每个节点拥有的链接数量(节点拥有的链接越多,节点的大小越大,反之亦然)。下面是我为节点编写的 JS。

如何根据链接数量更改节点大小?

var nodes = graph.nodes.slice(),
      links = [],
      bilinks = [];

  graph.links.forEach(function(link) {
    var s = nodes[link.source],
        t = nodes[link.target],
        i = {}; // intermediate node
    nodes.push(i);
    links.push({source: s, target: i}, {source: i, target: t});
    bilinks.push([s, i, t]);
  });

var node = svg.selectAll(".node")
      .data(graph.nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 3)
      .style("fill", function(d) { return color(d.group); })

enter image description here

最佳答案

您的问题对于具体答案来说有点不完整(您应该显示足够的代码来重现您正在做的事情),所以这里是一个基于 Bostock 经典 example 的概括问题。 。本质上,只需循环链接并计算节点链接的次数即可。然后使用这个计数来设置半径:

graph.links.forEach(function(link){

  // initialize a new property on the node
  if (!link.source["linkCount"]) link.source["linkCount"] = 0; 
  if (!link.target["linkCount"]) link.target["linkCount"] = 0;

  // count it up
  link.source["linkCount"]++;
  link.target["linkCount"]++;    
});

// use it to set radius
var node = svg.selectAll(".node")
  .data(graph.nodes)
  .enter().append("circle")
  .attr("class", "node")
  .attr("r", function(d){
     return d.linkCount ? (d.linkCount * 2) : 2; //<-- some function to determine radius
  });

完成运行code here .

关于javascript - D3 JavaScript 网络 : How to parametrize node size with the number of links?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173304/

相关文章:

javascript - 解绑后无法绑定(bind)

javascript - 在 D3 Javascript 中显示 .json map

javascript - 从 Json 数组中过滤值 (JavaScript)

javascript - D3V4 - 无法让 d3.tree 在 CodeSnippet 中工作

javascript - 为正负整数解析字符串,Javascript

javascript - 如何让 `rn-animated-progress-circle`无限循环

javascript - 最小输入值取决于第二个输入

javascript - Dropzone JS - 销毁并重新创建相同的表单

javascript - 如何通过给定的URL获取YouTube音频数据

javascript - D3 事件监听器返回 MouseEvent 而不是数据