看起来您的问题来自您将颜色映射到社区的方式。由于来自nx.draw_networkx_nodes 的node_color 参数预计是一个颜色列表(参见文档here),因此您需要将每个节点与其社区关联的颜色相关联。您可以使用以下方法做到这一点:
c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy))) #create a list of colors, one for each community
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))} #for each node associate the node with the color of its community
colors_sort=dict(sorted(colors.items())) #sort the dictionary by keys such
然后,您可以将排序字典的值转换为列表,并将其传递给 nx.draw_networkx_nodes 和 nx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))。
请参阅下面的完整代码:
import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom
import numpy as np
G = nx.karate_club_graph()
greedy = nxcom.greedy_modularity_communities(G)
c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy)))
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))}
colors_sort=dict(sorted(colors.items()))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos,labels={n:str(n) for n in G.nodes()})
plt.axis('off')
plt.show(G)