【问题标题】:NetworkX add node after spring_layout to the graphNetworkX 在 spring_layout 之后添加节点到图中
【发布时间】:2019-10-10 14:55:36
【问题描述】:

有以下代码:

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 图中?

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    问题(正如其他人已经指出的那样)是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()
    

    【讨论】:

      【解决方案2】:

      spring 布局的输出是一个字典,将节点映射到位置 {nodeid:[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]
      

      【讨论】:

      • 感谢这种方法,但其他解决方案似乎更好,而不是解决方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多