I am using NetworkX for analyzing a network G of transport connections. After visualizing it I saw that there are some "islands" of nodes that do not have any connections to the network. Those islands mostly consist of 2 to 5 nodes. Since the network is really big I am looking for a command that returns each of those islands, preferrably in a data structure that indicates the names of the nodes. The isolates(G)
command only returns nodes of degree zero, but I am interested in the islands. Is there a command for that?
Look into the connected_components
function
# Create three separate graphs and then compose them together.
import networkx as nx
G = nx.complete_graph(8)
G2 = nx.complete_graph(range(13, 15))
G3 = nx.complete_graph(range(16, 19))
G = nx.compose_all([G, G2, G3])
nx.draw(G)
Using connected_components()
:
list(nx.connected_components(G))
[{0, 1, 2, 3, 4, 5, 6, 7}, {13, 14}, {16, 17, 18}]
threshold = 6
[c for c in nx.connected_components(G) if len(c) < threshold]
[{13, 14}, {16, 17, 18}]
You can also check out connected_components_subgraph