【问题标题】:d3.js force directed graph: How to make node size depends on the value of the links?d3.js 强制有向图:如何使节点大小取决于链接的值?
【发布时间】:2017-11-16 20:02:18
【问题描述】:

我有这样的数据:

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 //
]

我一直在尝试根据链接中的value 设置节点半径大小,这些链接将节点称为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.filterI've taken from here。我正在使用 d3.js v4。

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

【问题讨论】:

标签: javascript d3.js d3-force-directed


【解决方案1】:

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

所以过滤器语句的目的似乎是根据索引在该数组中找到对应的链接。 没有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;
})

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 2012-09-17
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多