0

我有这样的数据:

var nodes = [
{
    "id": "A",
    "label": "Data A",
    "group": "0",
    "level": "0"
}, {
    "id": "B",
    "label": "Data B",
    "group": "1",
    "level": "1"
},
// etc //
]

var links = [
{
    "source": "A",
    "target": "B",
"strength": "0.5",
    "value": "276"
}, {
    "source": "A",
    "target": "C",
"strength": "0.5",
"value": "866"
},
// etc //
]

我一直在尝试根据将valuenode 作为其target.

因此,例如,节点 B 的大小应根据 276 的值(以节点 B 作为其目标的链接)。

这是我使用的:

var nodeElements = g.append("g") 
    .attr("class", "nodes")
    .selectAll("circle")
    .data(nodes)
    .enter().append("circle")
    .attr("r", function(node,link){
          var radius = 12;
          if (node.level == 0) radius = radius * 2; // Setting up the main node as bigger than others

          node.weight = link.filter(function(link) {
             if (link.target.index == node.index){
               var linkValue = link.value;
               if (linkValue > 500) ? (radius = 12) : (radius = 6);
             }
          });

          return radius;
      })
    .attr("fill", getNodeColor)
    .attr("stroke", "#fff")
    .attr('stroke-width', 2)
    .on('mouseover', selectNode)

但这似乎不起作用。说它不认识我从这里拿走的link.filter东西。我正在使用 d3.js v4。

试图寻找线索,但仍然没有任何线索。有任何想法吗?

4

1 回答 1

2

有几件事需要更改,但首先您应该了解您不会自动添加links到节点的数据中。

所以 filter 语句的目的似乎是在那个数组中,根据 index 找到对应的链接。没有link变量传递给外部函数,但您应该在links上面定义的数组中搜索一个链接,该链接的目标为节点 ID。

如果您只需要一个链接,而不是所有链接,请使用Array.prototype.find。但是filterfind以相同的方式工作 - 定义的匿名函数在数组中的每个项目上调用。find在第一个找到的对象处停止,同时filter返回所有匹配项。

.attr("r", function(dat, index, n) {
    var linkItem = links.find(function(link) {
        return link.target == dat.id;
    });
    var radius = 12;
    // linkItem would be undefined if the item was not found in the links
    if (linkItem && linkItem.value > 500) {
        radius = 12;
    } else {
        radius = 6;
    }

    // you should double the radius towards the end,
    // so that radius doesn't get overwritten
    if (dat.level === 0) {
        radius = 2 * radius;
    }

    return radius;
})
于 2017-11-16T20:40:03.140 回答