[英]How to fix the nodes position in networkx?
I have recently started to work with Networkx in python.我最近开始在 python 中使用 Networkx。 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
为了绘制图表,我使用以下 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.并在for循环中的主要function中,我将绘图称为function,但每次position的节点都会发生变化。 Now I want to know, is there any solution to fix the position of nodes in all drawings?
现在我想知道,有没有办法修复所有图纸中节点的position? If yes, how I can do it?
如果是,我该怎么做? this is the main function
这是主要的 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.下图是output的例子。 IF you consider the nodes based on their labels, the position of them is not fix.
如果您根据标签考虑节点,则它们的 position 不固定。
As @furas stated in the comments, in order to always obtain the same node positions you need to keep this as a variable, eg:正如@furas 在评论中所述,为了始终获得相同的节点位置,您需要将其保留为变量,例如:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.