我想用 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); })
最佳答案
您的问题对于具体答案来说有点不完整(您应该显示足够的代码来重现您正在做的事情),所以这里是一个基于 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/