简体   繁体   中英

Networkx: labels of nodes in plot

I have a networkx g, divided in some communties, stored in a dictionary, which has the following form:

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}

I'm trying to plot the network, highlighting the different communities. The code is:

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)

and I get the following 1 . How can I know which community (labelled from 0 to 5) is plotted in yellow, which in blue and so on (without diplaying the labels on the plot)?

you could make a dummy plot with colors from the node colormap

# 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')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM