I'm relatively new to python coding, and I am using the following code to produce a graph, with 40 nodes, and the layout of the nodes is given using this code:
pos = nx.circular_layout(graph_anchor, **kwargs)
The following code creates graph_anchor:
graph_anchor = convert_ebunch_to_graph(ebunch_anchor)
def convert_ebunch_to_graph(ebunch):
g = nx.DiGraph()
g.add_weighted_edges_from(ebunch)
My question is, how do I work out in what order the nodes are being graphed ie how do I work out how this code decides which nodes to put beside each other and what order to lay them out in?
From the source of 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
It seems that positions are generated by dividing 360 degrees by the number of nodes. which node ends up where is decided by this line:
pos = dict(zip(G, pos))
zip(G, pos) iterates through the nodes of the graph in order. and assigns positions to them. If you want to change the position, you need to change the order.
Example:
# 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)
Here, the first position that is assigned is that of node 0, then we go counterclockwise.
I could not find an easy way to change the order of the nodes in G, so here is a little workaround which creates a new graph with randomised order:
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)
So changing the order of the nodes inside the graph changes where they will end up in the circular layout.
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.