AEngineer
AEngineer

Reputation: 152

Hide all but selected connected nodes in D3 (v4) force graph

I have created a dynamically built force graph in D3. When I click on one of the links I want to only show that and all the connected links/nodes.

This Plunkr is a simplified version of what I have: http://plnkr.co/edit/TiKKmvydqXNipe103juL?p=preview (EDIT: I have updated this and is now a complete solution).

As you can see there are 3 separate 'groups' of connected nodes, in my real data set there are several hundred nodes and I want to be able to isolate an individual 'group' and only show that when the link which is part of that group is clicked on (it can't be the node that is clicked on as this shows a pop-up with more info).

I have been able to colour/hide connected links by pre-processing my data and using a rather complicated and long winded algorithm to determine whether the links are in the same connected group.

I have also been able to change the node that is clicked on or all the nodes/links by changing the dragstart function, this feels like I am getting close, but I don't think it recognises any link relationships.

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    // Changes all nodes/links
    d3.select("circle").classed("others",true).style("display","none"); 
    // Trying different ways to hide only 'other' nodes
    d3.selectAll("circle").classed("others",true).style("display","none"); 
    d3.selectAll("line").classed("others",true).style("display","none");

    d.fx = d.x;
    d.fy = d.y;
}

(I am aware of this question/answer how to highlight(change color) of all connected(neighbours) nodes and links in a d3 force directed graph but I don't think it really helps).

Any help would be appreciated.

Upvotes: 0

Views: 1278

Answers (1)

Oliver Houston
Oliver Houston

Reputation: 323

OK, this might be beyond me, but I think you somehow need to group your links into the same sorts of groups as your nodes. If you could somehow add the "group" attribute of the source node to the link, then when you click on the link something like this might work:

d3.selectAll("line")function fade(){if 
(group = "selected", "opacity" = 1)
else
("opacity" = 0)
};

alternatively, if you can sort the links into groups before the data is loaded (in your PHP etc. script), then you could append 3 (or n) groups of lines with separate classes.

Sorry, JS isn't my strongsuit, hopefully someone more experienced will sort that out for us...

Upvotes: 1

Related Questions