Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to fix the nodes position in networkx?

I have recently started to work with Networkx in python. I have a code which generates a network and based on some processes the nodes features changes. for example the colours and the statuses. for drawing the graph I use the following function

def draw_graph():
    colors = []
    for i in range (nCount):
        for j in range (i,nCount):
            if ifActive(i,j,timeStep) == 1 :
                
                    colors.append('r')
                  
                
            else :
                colors.append('g')
    color_map = []   
    nColor= nx.get_node_attributes(graph,'color')
    for nc in nColor:
        color_map.append(nColor[nc])   
    nx.draw(graph,pos=nx.spring_layout(graph), node_color = color_map, edge_color = colors,with_labels = True )

and in the main function in a for loop, I call the drawing function, but every time the position of nodes changes. Now I want to know, is there any solution to fix the position of nodes in all drawings? If yes, how I can do it? this is the main function

draw_graph()
for time in range(1,timeStep+1):
         if graph.node[i]["status"] == 1:
                settime(time,i)
        plt.figure(figsize=[10, 10], dpi=50)
        draw_graph()

the following figure is an example of output. IF you consider the nodes based on their labels, the position of them is not fix. enter image description here

question from:https://stackoverflow.com/questions/65645274/how-to-fix-the-nodes-position-in-networkx

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

1 Answer

0 votes
by (71.8m points)

As @furas stated in the comments, in order to always obtain the same node positions you need to keep this as a variable, e.g:

pos = nx.spring_layout(graph)

and then draw your graph as:

def draw_graph(p):
    # any code here, as long as no further nodes are added.
    nx.draw(graph,pos=p)

Then you can finally call it as:

pos = nx.spring_layout(graph)
draw_graph(pos)
# any code here, as long as no further nodes are added.
draw_graph(pos)
# each call will give the same positions.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...