如果我理解正确,您正在寻找“孤立”节点,这意味着节点不在图表的最大组成部分中。正如您所提到的,识别“孤立”节点的一种方法是查找不在最大组件中的所有节点。为此,您可以使用networkx.connected_components,获取组件列表并按大小对它们进行排序:
components = list(nx.connected_components(G)) # list because it returns a generator
components.sort(key=len, reverse=True)
然后你可以找到最大的组件,并获得“孤立”节点的计数:
largest = components.pop(0)
num_isolated = G.order() - len(largest)
我把这一切放在一个例子中,我画了一个鄂尔多斯-仁义随机图,将孤立节点着色为蓝色:
# Load modules and create a random graph
import networkx as nx, matplotlib.pyplot as plt
G = nx.gnp_random_graph(10, 0.15)
# Identify the largest component and the "isolated" nodes
components = list(nx.connected_components(G)) # list because it returns a generator
components.sort(key=len, reverse=True)
largest = components.pop(0)
isolated = set( g for cc in components for g in cc )
# Draw the graph
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos, nodelist=largest, node_color='r')
nx.draw_networkx_nodes(G, pos=pos, nodelist=isolated, node_color='b')
nx.draw_networkx_edges(G, pos=pos)
plt.show()