Issue
Trying to do something like this but I am not sure what I am doing incorrectly
import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom
G = nx.karate_club_graph()
greedy = nxcom.greedy_modularity_communities(G)
#returns a list with type frozen sets within the list
#[{set1},{set2},{set3}]
pos = nx.spring_layout(G) # compute graph layout
plt.axis('off')
nx.draw_networkx_nodes(G, pos, cmap=plt.cm.RdYlBu, node_color=list(greedy.values()))
plt.show(G)
Solution
It looks like your issue comes from the way you are mapping colors to your communities. Since the node_color
argument from nx.draw_networkx_nodes
is expected to be a list of color (see doc here), you will need to associate each one of your nodes with the color of its community. You can do that by using:
c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy))) #create a list of colors, one for each community
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))} #associate each node with the color of its community
colors_sort=dict(sorted(colors.items())) #sort the dictionary by keys such
You can then convert the values of your sorted dictionnary into a list and pass it to the nx.draw_networkx_nodes
with nx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))
.
See full code below:
import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom
import numpy as np
G = nx.karate_club_graph()
greedy = nxcom.greedy_modularity_communities(G)
c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy)))
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))}
colors_sort=dict(sorted(colors.items()))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos,labels={n:str(n) for n in G.nodes()})
plt.axis('off')
plt.show(G)
Answered By - jylls
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.