在D3中搜索元素 - 强制布局或树

nil*_*jan 5 tree highlight d3.js force-layout

是否有一个在d3js布局中搜索元素(强制定向或树)并突出显示该元素的示例?

我认为会有一个文本字段,用户输入要搜索的值.

Ale*_*lds 5

我写了一个工具,允许浏览生物监管网络,并排显示两个SVG面板.每个面板包含转录因子(节点)的力布局网络,如d3.js API所示.您可以输入转录因子的名称,它将使用与mouseover事件发生时使用的代码相同的代码突出显示它.探索代码可能会让您深入了解它是如何完成的.


Jak*_*eve 5

这是我提出的要点,也许相关?

我将我的实现分为 3 个步骤:

1) 在 select2 框中选择叶节点名称时,searchTree。

$("#search").on("select2-selecting", function(e) {
    var paths = searchTree(root,e.object.text,[]);
    if(typeof(paths) !== "undefined"){
        openPaths(paths);
    }
    else{
        alert(e.object.text+" not found!");
    }
})
Run Code Online (Sandbox Code Playgroud)

2)searchTree 返回一个节点数组,按照距离根节点(路径)的距离排序

function searchTree(obj,search,path){
    if(obj.name === search){ //if search is found return, add the object to the path and return it
        path.push(obj);
        return path;
    }
    else if(obj.children || obj._children){ //if children are collapsed d3 object will have them instantiated as _children
       var children = (obj.children) ? obj.children : obj._children;
       for(var i=0;i<children.length;i++){
            path.push(obj);// we assume this path is the right one
            var found = searchTree(children[i],search,path);
            if(found){// we were right, this should return the bubbled-up path from the first if statement
                return found;
            }
            else{//we were wrong, remove this parent from the path and continue iterating
                path.pop();
            }
        }
    }
    else{//not the right object, return false so it will continue to iterate in the loop
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

3) 通过将“._children”替换为“.children”来打开路径并添加类“found”以将所有内容着色为红色。(见链接和节点实例)

function openPaths(paths){
    for(var i=0;i<paths.length;i++){
        if(paths[i].id !== "1"){//i.e. not root
            paths[i].class = 'found';
            if(paths[i]._children){ //if children are hidden: open them, otherwise: don't do anything
                paths[i].children = paths[i]._children;
                paths[i]._children = null;
            }
            update(paths[i]);
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

我意识到这可能不是执行此操作的最佳方法,但是嘿,完成工作:)


PBr*_*ann 5

我已经使用基于select2的搜索小部件编写了一个解决方案.
您可以找到其路径扩展为红色的节点.
树被充分探索并且可以找到多个答案.

可折叠树搜索
https://gist.github.com/PBrockmann/0f22818096428b12ea23

希望能帮
帕特里克