Skip to content Skip to sidebar Skip to footer

How To Use Networkx's Rescale_layout?

I am having a hard time understanding how to use NetworkX's rescale_layout. The documentation says: pos (numpy array) – positions to be scaled. Each row is a position which is no

Solution 1:

This is a example of your layout:

pos = nx.random_layout(G)

and it's assigned to a dictionary that looks like:

{0: array([0.81931883, 0.8001609 ], dtype=float32), 
 1: array([0.89695644, 0.6070644 ], dtype=float32), 
 2: array([0.89160234, 0.47174907], dtype=float32), 
 3: array([0.20430276, 0.8206253 ], dtype=float32), 
 4: array([0.27929142, 0.08657268], dtype=float32)}

Now, since input of nx.rescale_layout() should be numpy array, you can extract it using a command

np.array(list(pos.values()))

Note that this way might be different on other versions of Python. I'll give an illustration of what have changed after pos parameter is rescaled:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

G = nx.Graph()
G.add_edges_from([[0,1],[1,2],[2,3],[3,4],[4,0]])
pos = nx.random_layout(G)
coords = np.array(list(pos.values()))

fig, ax = plt.subplots()
plt.subplot(211)
nx.draw_networkx(G, pos, with_labels=True)
plt.axis('on'); plt.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True) #force axis to turn on

plt.subplot(212)
new_pos = nx.rescale_layout(coords)
nx.draw_networkx(G, new_pos, with_labels=True)
plt.axis('on'); plt.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True) #force axis turn on
plt.show()

enter image description here

Post a Comment for "How To Use Networkx's Rescale_layout?"