在 Python 中使用 Girvan Newman 算法时根据社区颜色节点

Color Nodes According the Communities when using Girvan Newman Algorithm in Python

在下面的代码中,我想根据 girvan newman 算法给出的社区为节点着色。

G = nx.karate_club_graph()
posi_gn = nx.spring_layout(G)
comp = community.girvan_newman(G)
posi_gn = nx.spring_layout(G)

nx.draw_networkx(G, posi_gn, with_labels=True,  arrows=True, font_color='gray')
plt.show()

这取决于您要定义社区的级别,即您要定义多少个社区。知道了这一点,您可以按社区定义的组绘制节点:

G = nx.path_graph(10)
posi_gn = nx.spring_layout(G)
comp = nx.community.girvan_newman(G)

k = 3   # number of communities
for _ in range(k-1):
    comms = next(comp)

colors = 'rgb'
for nodes, c in zip(comms, colors):
    nx.draw_networkx_nodes(G, posi_gn, nodelist=nodes, node_color=[c], with_labels=True, arrows=True, font_color='gray')
nx.draw_networkx_edges(G, posi_gn)

查看 documentation 了解更多信息。