In the following dictionary mapping nodes to color, I wanted to draw the resultant graph whilst clustering the nodes within the graph based on their color. That is if node <
This can be achieved by slightly adapting the logic in the linked question. Note that I have altered the radius value for the center circle, as the graph has so many nodes and edges, as well as increasing the size of the figure. In addition, I have altered the logic to accept the dictionary input in the question. When plotting the nodes, I have added a black border to the nodes with edgecolors=[(0,0,0,1)]
as some nodes are white or off-white which made them hard to see.
Code:
import networkx
import numpy as np
import matplotlib.pyplot as plt
# Set up graph, adding nodes and edges
RRR = nx.Graph()
RRR.add_nodes_from(nodesWithGroup.keys())
RRR.add_edges_from(edges)
# Create a dictionary mapping color to a list of nodes
nodes_by_color = {}
for k, v in nodesWithGroup.items():
if v not in nodes_by_color:
nodes_by_color[v] = [k]
else:
nodes_by_color[v].append(k)
# Create initial circular layout
pos = nx.circular_layout(RRR)
# Get list of colors
colors = list(nodes_by_color.keys())
# OPTIONAL: shuffle colors list to get a random arrangement of colors
# import random
# random.shuffle(colors)
# Apply logic from linked answer: https://stackoverflow.com/a/55764135/12366110
# Note altered radius value. In addition, we get the value of posx from the colors list.
angs = np.linspace(0, 2*np.pi, 1+len(colors))
repos = []
rad = 13
for ea in angs:
if ea > 0:
repos.append(np.array([rad*np.cos(ea), rad*np.sin(ea)]))
for color, nodes in nodes_by_color.items():
posx = colors.index(color)
for node in nodes:
pos[node] += repos[posx]
# Plot graph
plt.figure(figsize=(20,20))
for color, nodes in nodes_by_color.items():
nx.draw_networkx_nodes(RRR, pos=pos, nodelist=nodes, node_color=color, edgecolors=[(0,0,0,1)])
nx.draw_networkx_edges(RRR, pos=pos)
plt.show()
Output: