How to approach filtering nodes and edges rendered

2020-03-27 08:01发布

问题:

Link to my code (Plunker)

I am developing a network diagram in D3.js force layout for academic purpose. I have so far coded a graph which displays nodes and edges. I have an auto-complete text box in jquery where user can enter a node name.

D3.js (Only part of code. For complete code see my plunker link):

var force = d3.layout.force()
  .nodes(d3.values(nodes))
  .links(links)
  .size([width, height])
  .linkDistance(100)
  .charge(-1546)
  .on("tick", tick)
  .start();

var svg = d3.select("#schemio")
  .append('svg')
  .attr("width", width)
  .attr("height", height);

var link = svg.selectAll(".link")
  .data(force.links())
  .enter().append("line")
  .attr("class", "link");

var node = svg.selectAll(".node")
  .data(force.nodes())
  .enter().append("g")
  .attr("class", "node")
  .call(force.drag);

HTML:

<div class="ui-widget">
    <label for="tags">Filter: </label>
    <input id="tags">
</div>

Jquery (Autocomplete)

$(function() {
    $( "#tags" ).autocomplete({
      source: nodesArray
    });
});

I want a functionality where when a user enters a node name in the filter box, I need to remove all other nodes and edges in the graph and keep only that particular node and its directly associated nodes and edges (one hop).

Example:

When I type "Parent" in the filter box it has to remove all other nodes and edges and keep only "Parent" node and its direct child nodes (child1, child2, child3).

What is a viable approach for filtering nodes and edges as the user searches for particular terms?

Thanks in advance.

回答1:

In essence, what a user is doing by searching for a specific node name is to narrow the data the visualization is going to show.

The approach

  1. First you need to narrow down the source data by using filtering or whatever makes sense in your situation. You end up with filtered data.
  2. Then you need to selectAll the nodes that have been drawn already and join the selection with filtered data from step 1.
  3. Finally use the d3 enter, update and exit selections to add, update and remove nodes and links.

Example

Mike Bostock published an example of [Modifying a Force Layout].(https://bl.ocks.org/mbostock/1095795)