Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - networkx add_node with specific position

I am still a beginner with networkx I want to add multiple types of nodes in different position, I used the following code

pos = {0: (40, 20), 1: (20, 30), 2: (40, 30), 3: (30, 10)} 
X=nx.Graph()
nx.draw_networkx_nodes(X,pos,node_size=3000,nodelist=[0,1,2,3],node_color='r')

but when I want to access the Graph X , if I type X.node it returns an empty list and if I want to add more nodes I have to set their positions in the beginning using pos dictionary.

How can I add nodes to a graph in a specific location x and y using add_node()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the following approach to set individual node positions and then extract the "pos" dictionary to use when drawing.

In [1]: import networkx as nx

In [2]: G=nx.Graph()

In [3]: G.add_node(1,pos=(1,1))

In [4]: G.add_node(2,pos=(2,2))

In [5]: G.add_edge(1,2)

In [6]: pos=nx.get_node_attributes(G,'pos')

In [7]: pos
Out[7]: {1: (1, 1), 2: (2, 2)}

In [8]: nx.draw(G,pos)

UPDATE

Add drawing

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...