Reputation: 14684
Still kinda new to NetworkX here, but I wanted to be able to query a NetworkX graph to find all nodes within a cluster of nodes. Here is an example graph I had generated:
As you can see, there are clusters of nodes. Within each cluster, every node is connected to every other node. You can see that in a zoom-up of five such clusters below:
I'd like to be able to find out how I can extract out each individual cluster of nodes. Each node is named with a long name ("A/Vietnam/2009/8/431", for example), and I know how to fish out an individual node using NetworkX's functions, but I don't know how to get all connected nodes within that cluster. Language of preference is Python (2.7), and I have been using the NetworkX package in conjunction.
Thanks everybody!
Upvotes: 8
Views: 9094
Reputation: 1775
import networkx as nx
from networkx.algorithms.components import connected_components
n = 10
G = nx.empty_graph(n)
# G is the networkx graph
subgraphs = [G.subgraph(c) for c in connected_components(G)]
# n gives the number of subgraphs
n_subgraphs = len(subgraphs)
# you can now loop through all nodes in each subgraph
for i in range(n_subgraphs):
print(f"Subgraph: {i} consists of {subgraphs[i].nodes()}")
Upvotes: 15
Reputation: 311
Update for Python 3.x:
import networkx as nx
# Identify groups of connected components (or subgraphs)
sub_graphs = nx.connected_components(G)
# Loop through all nodes in each subgraph and display them
while True:
try:
print(next(sub_graphs))
except StopIteration:
break
Upvotes: 2