Group Nodes Together In Networkx
I have a visualization problem involving a graph. I have N nodes, which belong to say some M networks. The nodes can have inter-network edges (within the same network) and intra-ne
Solution 1:
To get better nodes layout, I start with using circular layout (replacing your spring-layout). Then I move each group of the nodes to their new locations along perimeter of a bigger circle.
# --- Begin_myhack ---# All this code should replace original `pos=nx.spring_layout(graph)`import numpy as np
pos = nx.circular_layout(graph) # replaces your original pos=...# prep center points (along circle perimeter) for the clusters
angs = np.linspace(0, 2*np.pi, 1+len(colors))
repos = []
rad = 3.5# radius of circlefor ea in angs:
if ea > 0:
#print(rad*np.cos(ea), rad*np.sin(ea)) # location of each cluster
repos.append(np.array([rad*np.cos(ea), rad*np.sin(ea)]))
for ea in pos.keys():
#color = 'black'
posx = 0if ea in nodes_by_color['green']:
#color = 'green'
posx = 0elif ea in nodes_by_color['royalblue']:
#color = 'royalblue'
posx = 1elif ea in nodes_by_color['red']:
#color = 'red'
posx = 2elif ea in nodes_by_color['orange']:
#color = 'orange'
posx = 3elif ea in nodes_by_color['cyan']:
#color = 'cyan'
posx = 4else:
pass#print(ea, pos[ea], pos[ea]+repos[posx], color, posx)
pos[ea] += repos[posx]
# --- End_myhack ---
The output plot will be similar to this:
EDIT
Usually, no particular layout is best in all situations. So, I offer the second solution which uses concentric circles to separate individual groups of the nodes. Here are the relevant code and its sample output.
# --- Begin_my_hack ---# All this code should replace original `pos=nx.spring_layout(graph)`import numpy as np
pos = nx.circular_layout(graph)
radii = [7,15,30,45,60] # for concentric circlesfor ea in pos.keys():
new_r = 1if ea in nodes_by_color['green']:
new_r = radii[0]
elif ea in nodes_by_color['royalblue']:
new_r = radii[1]
elif ea in nodes_by_color['red']:
new_r = radii[2]
elif ea in nodes_by_color['orange']:
new_r = radii[3]
elif ea in nodes_by_color['cyan']:
new_r = radii[4]
else:
pass
pos[ea] *= new_r # reposition nodes as concentric circles# --- End_my_hack ---
Post a Comment for "Group Nodes Together In Networkx"