来自nx.circular_layout的来源:
def circular_layout(G, dim=2, scale=1, center=None):
# dim=2 only
"""Position nodes on a circle.
Parameters
----------
G : NetworkX graph or list of nodes
dim : int
Dimension of layout, currently only dim=2 is supported
scale : float
Scale factor for positions
center : array-like or None
Coordinate pair around which to center the layout.
Returns
-------
dict :
A dictionary of positions keyed by node
Examples
--------
>>> G=nx.path_graph(4)
>>> pos=nx.circular_layout(G)
Notes
------
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.
"""
import numpy as np
G, center = process_params(G, center, dim)
if len(G) == 0:
pos = {}
elif len(G) == 1:
pos = {G.nodes()[0]: center}
else:
# Discard the extra angle since it matches 0 radians.
theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
theta = theta.astype(np.float32)
pos = np.column_stack([np.cos(theta), np.sin(theta)])
pos = _rescale_layout(pos, scale=scale) + center
pos = dict(zip(G, pos))
return pos
似乎位置是通过将 360 度除以节点数来生成的。
哪个节点最终在哪里由这一行决定:
pos = dict(zip(G, pos))
zip(G, pos) 按顺序遍历图的节点。并为他们分配职位。如果你想改变位置,你需要改变顺序。
例子:
# make dummy graph
G = nx.from_numpy_array(np.random.rand(12,12)>0.5)
# test order of nodes:
for node in G.nodes:
print(node)
0
1
2
3
4
5
6
7
8
9
10
11
pos = nx.circular_layout(G)
nx.draw_networkx(G, pos=pos)
这里,分配的第一个位置是节点0的位置,然后我们逆时针走。
我找不到一种简单的方法来更改 G 中节点的顺序,所以这里有一个小变通方法,它可以创建一个具有随机顺序的新图:
nodes = list(G.nodes(data=True))
edges = list(G.edges(data=True))
np.random.shuffle(nodes)
H=nx.Graph()
H.add_nodes_from(nodes)
H.add_edges_from(edges)
pos = nx.circular_layout(H)
nx.draw_networkx(H, pos=pos)
因此,更改图中节点的顺序会改变它们在圆形布局中的最终位置。