d3基于用户选择动态更新节点

d3 dynamically updating nodes based on user selection

本文关键字:选择 动态 更新 节点 用户 于用户 d3      更新时间:2023-09-26

我试图让用户点击强制布局中的节点,并将数据集减少到只有这些节点及其关联链接。

我已经走到了这一步;http://jsfiddle.net/hiwilson1/4gemo0xe/1/

从179开始的部分;

d3.select("#filterResults")
    .on("click", function() {
        //feed the indexes of the selected nodes into array
        var nodeArray = []
        d3.selectAll("circle[fill='"Red'"]")
            .each(function(d, i) {
                    nodeArray.push(d3.select(this).attr("node-index"))              
            })
        //step2: loop through nodes array and return only those nodes that share
        //index with nodeArray into newNodes
        var newNodes = []
        nodes.forEach(function(nde, idx, list) {
            nodeArray.forEach(function(nde2, idx2, list2) {
                if (idx == nde2) {
                     newNodes.push(nde)   
                }
            })
        })
        //step3: loop through links array and return only those links that
        //have source or target as index of nodes in nodeArray
        var newLinks = []
        links.forEach(function(link, lidx, llist) {
            nodeArray.forEach(function(nde, idx, list) {
                if (link.source == nde || link.target == nde) {
                        newLinks.push(link)
                }
            })
        })
        alert(newLinks.length)
    })

是我被卡住的地方,特别是第3步。我似乎无法从onclick函数中获取链接,无论有多少链接与所选节点关联,警报都会在应该返回的位置返回零。

最终,如果可能的话,我想识别与所选内容相关的节点和链接,然后更新数据集以反映这个新的数据集!只有一种方法可以找到。。

一旦启动强制,源值和目标值就会被相应的节点对象替换。因此,与其将链接源与节点索引进行比较,不如将其与节点进行比较。

if (link.source == nodes[nde] || link.target == nodes[nde]) {
    newLinks.push(link)
}

if (link.source.index == nde || link.target.index ==nde) {
    newLinks.push(link)
}

更新的JSFiddle

注意:源属性和目标属性的值最初可能是指定为节点数组中的索引;这些将由调用之后的引用以启动。

这是节点的示例结构。

{
    fixed: 0,
    index: 12,
    label: "I am an information label",
    px: 287.64956227452404,
    py: 83.71383910494417,
    weight: 7,
    x: 287.7214898272057,
    y: 83.59069881862021
}

d3.select(".node").data()将返回与该节点关联的数据,其中node是类名。

你可以从这里了解更多关于d3力布局的信息。