在边界框中绘制 networkx 图

Plot a networkx graph in a bounding box

我想在边界为 (100, 100) 的二维网格中生成 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中的节点坐标 这样所有节点都位于边界内。

一种方法是使用 nx.spring_layout

scalecenter 参数
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])}