NetworkX在使用spring_layout布局后添加节点到图形中。

3

有以下代码:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_nodes_from(range(1, 10))
G.add_edges_from([(1, 3), (2, 4), (3, 4), (2,6), (1, 2), (4, 9), (9, 1)])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
G.add_node(10)
nx.draw(G, pos, with_labels=True) # this gives the error
plt.show()

如何将节点10添加到图形的随机位置?我实际遇到的错误是:

NetworkXError:节点10没有位置。

如何在已经构建spring_layout的图形中包含新创建的节点?

2个回答

4
(他人已经指出的)问题在于“pos”是将每个节点分配一个位置的字典。但是当你添加一个节点时,它不会更新“pos”。
以下代码将根据所有其他节点的现有位置找到新节点10的良好位置。基本上,它再次调用了“spring_layout”,但保持所有现有节点不动。我将节点10连接到节点9。
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_nodes_from(range(1, 10))
G.add_edges_from([(1, 3), (2, 4), (3, 4), (2,6), (1, 2), (4, 9), (9, 1)])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()

G.add_node(10)
G.add_edge(9,10)  #So node 10 should be close to node 9
oldnodes = list(G.nodes())
oldnodes.remove(10)
pos = nx.spring_layout(G, pos=pos, fixed=oldnodes)

nx.draw(G, pos, with_labels=True) 
plt.show()

3
从Spring布局的输出得到了一个将节点映射到位置{x,y}的字典。为了随机放置新节点,必须在pos字典中给它一个随机位置。
下面是一个示例,它找到边界框,然后在其中选择一个随机点。
import numpy as np

bounds = np.zeros((2,2)) # xy min, xymax

for pt in pos.values():
    bounds[0] = np.min([bounds[0],pt], axis=0) # compare point to bounds and take the lower value
    bounds[1] = np.max([bounds[1],pt], axis=0) # compare point to bounds and take the highest value

pos[10] = (bounds[1] - bounds[0]) * np.random.random(2)  + bounds[0]

谢谢您提供这种方法,但另一种解决方案似乎更好,而不是一个临时的解决办法。 - Damian-Teodor Beleș

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接