question copy-pasta from SO:
---
I am using a d3 force-directed graph that produces a hairball of data. :-)
I think it's either this one: http://bl.ocks.org/1138500 or this one: http://bl.ocks.org/4062045 (I inherited this so not exactly sure but these 2 visualizations are really similar!)
When I click a node, I'd like to zoom in on, or redraw the graph based on just that node. So on click of a node, the other nodes and edges would disappear. How can I do that? I'm using Ruby on Rails and Neo4j, so a cypher query is creating the JSON data that d3 uses.
Will i have to re-query the database via cypher? I hope not. I'm hoping that this can be done in d3.js alone.
Thanks in advance for your ideas. If you have a working example, I'd love to see it!
---
answer:
This can be done entirely in D3 / JavaScript. As the major power of D3 is in animating your data visualizations, it is to be expected that D3 can handle this task of showing/hiding nodes/clusters.
There are several ways to tackle this; it depends on how you want to visualize the transition.
which is solving a very similar problem to yours; the 'magick trick' is that it regenerates the force nodes + links arrays when a cluster node is clicked; in your case that approach would then filter the node(s) ou want to display and remove the rest from the nodes + links sets. (Keep a copy of the full sets as obtained from the server so you can 'revert' the action on user request, similar to clicking again on the cluster-node in the example above.
(There are more collapsible tree/force-layout gists out there, including several of mine, but those aren't really suited as 'starter' material)
[Since you say you 'inherited this', so I assume you don't have previous experience with D3:] Concerning the animation happening in the gist linked above (and in a LOT of other demos): read up on the D3 data enter/exit/update mechanism in this article:
http://bost.ocks.org/mike/join/
I cannot overstate the importance of understanding what's written in that article as it is the fundamental building block underpinning all animation logic in D3.
When you've read that article, have another look at that linked gist (and possibly others) and see the .enter() and exit()'s at work. ;-)
There are also other ways to tackle this issue, but the most flexible option is via regenerating the nodes/links collections on user mouse click event and then restarting the force layout logic again via force.start().
Sophisticated example of the show/hide logic (plus a few more things):
http://bl.ocks.org/GerHobbelt/3637711 (not suitable to learn from as a beginner, though. This just shows how far you can take an otherwise simple concept.)