【问题标题】:Plot a networkx graph in a bounding box在边界框中绘制 networkx 图
【发布时间】:2021-12-04 17:07:58
【问题描述】:

我想在具有边界 (100, 100) 的 2D 网格中生成 NetworkX 图,即 x 轴范围为 (0,100),y 轴范围为 (0,100)。

import matplotlib.pyplot as plt
import networkx as nx


H = nx.gnm_random_graph(n=8, m=9, seed=5)  # generate a random graph
pos = nx.spring_layout(H, iterations=500)  # find good positions for nodes
nx.draw(H)
print(pos)
plt.show()

我想知道如何缩放存储在pos 中的节点坐标 使得所有节点都在边界内。

【问题讨论】:

    标签: python python-3.x graph networkx bounding-box


    【解决方案1】:

    一种方法是使用nx.spring_layout 的scale 和center 参数

    pos = nx.spring_layout(H, iterations=500, scale=50, center=(50, 50))  # find good positions for nodes
    
    # verify positions are withing boundaries 
    positions_array = np.array(list(pos.values()))
    print(((0 <= positions_array) & (positions_array <= 100)).all())
    

    输出

    True
    

    对应的pos 结果(一次运行)为:

    {0: array([69.42667319, 77.61143687]), 1: array([81.63688581, 10.64742778]), 2: array([56.9561371,  0.       ]), 3: array([71.3536673 , 41.34120577]), 4: array([16.61575096, 54.76920418]), 5: array([17.06331411, 87.49081365]), 6: array([41.68768891, 28.49815199]), 7: array([45.25988262, 99.64175977])}
    

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 1970-01-01
      • 2022-11-12
      • 2022-01-02
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多