简体   繁体   中英

Plot a networkx graph in a bounding box

I would like to generate a NetworkX graph in a 2D grid with boundaries (100, 100) ie x-axis ranges from (0,100) and y-axis ranges from (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()

I would like to know how to scale the coordinates of nodes stored in pos such that all nodes lie within boundary.

One approach is to use the scale and center arguments of nx.spring_layout

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())

Output

True

The corresponding pos result (for one run) was:

{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])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM