networkx.drawing.layout.spring_layout¶
-
spring_layout(G, k=None, pos=None, fixed=None, iterations=50, threshold=0.0001, weight='weight', scale=1, center=None, dim=2, seed=None)¶ Position nodes using Fruchterman-Reingold force-directed algorithm.
The algorithm simulates a force-directed representation of the network treating edges as springs holding nodes close, while treating nodes as repelling objects, sometimes called an anti-gravity force. Simulation continues until the positions are close to an equilibrium.
There are some hard-coded values: minimal distance between nodes (0.01) and “temperature” of 0.1 to ensure nodes don’t fly away. During the simulation,
khelps determine the distance between nodes, thoughscaleandcenterdetermine the size and place after rescaling occurs at the end of the simulation.Fixing some nodes doesn’t allow them to move in the simulation. It also turns off the rescaling feature at the simulation’s end. In addition, setting
scaletoNoneturns off rescaling.- Parameters
G (
NetworkX graphorlistofnodes) – A position will be assigned to every node in G.k (
float (default=None)) – Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.pos (
dictorNone optional (default=None)) – Initial positions for nodes as a dictionary with node as keys and values as a coordinate list or tuple. If None, then use random initial positions.fixed (
listorNone optional (default=None)) – Nodes to keep fixed at initial position. ValueError raised iffixedspecified andposnot.iterations (
int optional (default=50)) – Maximum number of iterations takenthreshold (
float optional (default = 1e-4)) – Threshold for relative error in node position changes. The iteration stops if the error is below this threshold.weight (
stringorNone optional (default=``’weight’``)) – The edge attribute that holds the numerical value used for the edge weight. If None, then all edge weights are 1.scale (
numberorNone (default:1)) – Scale factor for positions. Not used unlessfixed is None. If scale is None, no rescaling is performed.center (
array-likeorNone) – Coordinate pair around which to center the layout. Not used unlessfixed is None.dim (
int) – Dimension of layout.seed (
int,RandomState instanceorNone optional (default=None)) – Set the random state for deterministic node layouts. If int,seedis the seed used by the random number generator, if numpy.random.RandomState instance,seedis the random number generator, if None, the random number generator is the RandomState instance used by numpy.random.
- Returns
pos – A dictionary of positions keyed by node
- Return type
Examples
>>> G = nx.path_graph(4) >>> pos = nx.spring_layout(G)
# The same using longer but equivalent function name >>> pos = nx.fruchterman_reingold_layout(G)