Python Networkx:绘图中节点的标签

Python Networkx:绘图中节点的标签,python,networkx,Python,Networkx,我有一个networkx g,分为一些社区,存储在字典中,其形式如下: partition={465: 0, 928: 4, 113: 2, 333: 0, 679: 3, 1141: 4, 503: 0, 1017: 4, 1214: 3, 800: 1, 266: 5, 1052: 4, 27: 2, 580: 3, 948: 1, 1102: 4, 270: 5, 657: 3, 546: 3, 1087: 4, 589: 3, 1172: 4, 881: 1, 924: 2, 433:

我有一个networkx g,分为一些社区,存储在字典中,其形式如下:

partition={465: 0, 928: 4, 113: 2, 333: 0, 679: 3, 1141: 4, 503: 0, 1017: 4, 1214: 3, 800: 1, 266: 5, 1052: 4, 27: 2, 580: 3, 948: 1, 1102: 4, 270: 5, 657: 3, 546: 3, 1087: 4, 589: 3, 1172: 4, 881: 1, 924: 2, 433: 3, 403: 0, 592: 3, 579: 3, 260: 5, 666: 3, 972: 4, 753: 0, 626: 3, 1013: 4, 891: 1, 210: 5, 109: 2, 1029: 4, 506: 3, 435: 3, 277: 5, 1198: 0, 492: 0, 688: 3, 377: 5}
我试图绘制网络图,突出不同的社区。代码是:

pos = nx.spring_layout(g)  # graph layout
plt.figure(figsize=(8, 8))  # 8 x 8 inches
plt.axis('off')
nx.draw_networkx_nodes(g, pos, node_size=25, node_color=list(partition.values()))
nx.draw_networkx_edges(g, pos, alpha=0.05)
我得到了以下结论。
我如何知道哪个社区(标记为0到5)以黄色绘制,哪个社区以蓝色绘制,依此类推(无需在绘图上放置标签)?

您可以使用节点颜色贴图中的颜色创建虚拟绘图

# dummy data
g = nx.from_numpy_matrix(np.random.randint(0,2,size=(100,100)))
partition = {a:np.random.randint(0,6) for a in g.nodes()}

pos = nx.spring_layout(g)  # graph layout
plt.figure(figsize=(8, 8))  # 8 x 8 inches
plt.axis('off')
## assign the output of nx.draw_networkx_nodes to a variable to call its colormap
nodes = nx.draw_networkx_nodes(g, pos, node_size=25, node_color=list(partition.values()))
nx.draw_networkx_edges(g, pos, alpha=0.05)

values = sorted(list(set(partition.values())))
for v in values:
    # make dummy scatterplot to generate labels
    plt.gca().scatter([],[], color=nodes.cmap(v/np.max(values)), label=v)
    
plt.legend(loc='lower right')