D3力导向图 - 过滤节点和相关链接

时间:2016-10-26 17:09:35

标签: javascript d3.js

我正在尝试在力导向图上使用过滤器时遇到困难。我可以过滤掉节点,但不能使关联的链接消失。我对JavaScript的了解非常有限,但我猜逻辑应该是:如果节点被隐藏,则隐藏相关链接。我在正确的道路上吗? 如果有人可以帮助我,我将不胜感激!

数据格式:

{
  "nodes": [
{"name":"AA1","group":"Group1","type":"a"},
{"name":"AA2","group":"Group2","type":"b"},
{"name":"AA3","group":"Group3","type":"c"},
{"name":"AA4","group":"Group4","type":"a"},
{"name":"AA5","group":"Group2","type":"b"},
{"name":"AA6","group":"Group4","type":"c"},...
],
  "links": [
{"source":1,"target":59,"value":1},
{"source":1,"target":88,"value":1},
{"source":3,"target":12,"value":1},
{"source":3,"target":16,"value":1},
{"source":3,"target":87,"value":1},
{"source":5,"target":3,"value":1},
{"source":5,"target":16,"value":1},
{"source":5,"target":114,"value":1},...  ]

过滤器代码:

 // call method to create filter
createFilter();
// method to create filter
function createFilter()
{
    d3.select(".filterContainer").selectAll("div")
      .data(["a", "b", "c"])
      .enter()
      .append("div")
          .attr("class", "checkbox-container")
      .append("label")
      .each(function(d) {
         // create checkbox for each data
      d3.select(this).append("input")
        .attr("type", "checkbox")
        .attr("id", function(d) {return "chk_" + d;})
        .attr("checked", true)
        .on("click", function(d, i) {
            // register on click event
            var lVisibility = this.checked? "visible":"hidden";
            filterGraph(d, lVisibility);
        })
        d3.select(this).append("span")
          .text(function(d){return d;});
      });

      $("#sidebar").show();  // show sidebar
}

 // Method to filter graph
function filterGraph(aType, aVisibility)
{   
 // change the visibility of the node

    node.style("visibility", function(o) {
    var lOriginalVisibility = $(this).css("visibility");
    return o.type === aType ? aVisibility : lOriginalVisibility;
    }); 

/////////////////////////////////////// 需要代码隐藏链接 //////////////////////////////////////

}

1 个答案:

答案 0 :(得分:1)

您需要通过检查其源或目标是否未被选中来隐藏链接。所以在你的filterGraph部分中,添加类似的东西(假设你的链接有class =“link”):

0x8180255

以Mike Bostock的悲惨为例,我使用上面的代码来过滤除了连接“Dahlia”和“Tholomyes”之外的所有其他代码。

enter image description here

以下是jsfiddle示例的片段:

positive = ["Dahlia", "Tholomyes"];
link.attr("display", function (o) {

////Here the structure of the the link can vary, sometimes it is o["source"]["name"], sometimes it is o["source"]["name"], check it out before you fill in.
var source_name = o["source"]["id"];
var target_name = o["target"]["id"];

var result = positive.indexOf(source_name) != -1 && positive.indexOf(target_name) != -1 ? "auto" : "none"

return result;

});