简体   繁体   中英

Center labling for nodes of a graph with networkx

import networkx as nx
import matplotlib.pyplot as plt

usernode = input("How many node does your graph have?")
G = nx.Graph()
nodenum = []
labels = {}
for node in range(usernode):
    nodenum.append(node)
for label in range(usernode):
    labels[label] = str(label)
print(labels)

G.add_nodes_from(nodenum)
pos = nx.spring_layout(G)
nx.draw_networkx_labels(G,pos,labels,font_size = 10)
nx.draw(G)
plt.axis('off')
plt.show()

1.How can I put the label of this nodes exactly center of the circles?I know this issue is about the pos but what should I do? 2.Totally How can i manage the pos in networkx? Thanks

  1. The problem is that you are drawing the labels with given positions then you draw the graph without specifying any node positions so networkx generates its own positions. So, you can do one of the two options to solve it:

a) send pos to nx.draw function: nx.draw(G,pos) instead of nx.draw(G)

OR more simply

b) remove the nx.draw_networkx_labels line and change nx.draw(G) to nx.draw(G,pos,with_labels=True,font_size = 10)

  1. you have different layouts like the spring one that you used, you can find them here . Or you can generate you own positions by creating a dictionary key by node.

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