如何解决如何修复networkx中的节点位置?
我最近开始在 python 中使用 Networkx。我有一个代码,它生成一个网络,并根据一些过程节点功能发生变化。例如颜色和状态。为了绘制图形,我使用以下函数
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 )
并且在for循环的main函数中,我调用了绘图函数,但是每次节点的位置都会发生变化。现在我想知道,有没有什么办法可以修复所有图纸中节点的位置?如果是,我该怎么做? 这是主要功能
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()
下图是输出示例。如果您根据标签考虑节点,则它们的位置不是固定的。
解决方法
正如@furas 在评论中所述,为了始终获得相同的节点位置,您需要将其保留为变量,例如:
pos = nx.spring_layout(graph)
然后将图形绘制为:
def draw_graph(p):
# any code here,as long as no further nodes are added.
nx.draw(graph,pos=p)
那么你终于可以称之为:
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。