Home > Back-end >  How to extend a list of elements and draw them
How to extend a list of elements and draw them

Time:11-24

I detected some communities in a network and I would like to make the process as more automated as possible, especially when a big number of communities is detected. The code I used is

from networkx.algorithms.community.modularity_max 
import greedy_modularity_communities

c = list(greedy_modularity_communities(G))

That detects 3 communities. To see the clusters and plot them, I usually run the following:

community_0 = sorted(c[0])
community_1 = sorted(c[1])
community_2 = sorted(c[2])

And to draw each set of nodes:

nx.draw_networkx_nodes(G,circ_pos, nodelist=community_0, node_color='g', alpha=0.5)
nx.draw_networkx_nodes(G,circ_pos, nodelist=community_1, node_color='r', alpha=0.5)
nx.draw_networkx_nodes(G,circ_pos, nodelist=community_2, node_color='b', alpha=0.5)

where G is G = nx.karate_club_graph(). My question is how to extend the list of community_x, i.e.,the x communities that can be detected using greedy_modularity_communities, and draw them, adding iteratively the parameter in the nodelist.

CodePudding user response:

Use python eval() function and make a search in meta programming concept.

I provide some sample code for you:

for i in range(1,3):
    eval('community_' str(i) ' = sorted(c[' str(i) ']))'

CodePudding user response:

I would do it like this:

from networkx.algorithms.community.modularity_max 
import greedy_modularity_communities

# list of detected communities 
c = list(greedy_modularity_communities(G))
sortedCommunities = []

# iterate through list of discovered communities. Sort each community and add them to new list.

for community in c:
    sortedCommunities.append(sorted(community))

# draw community
# here we are using a different color at each iteration but cycling back to the first color.

colors = ['g', 'r', 'b']
temp_counter = 0
for community in sortedCommunities:
    
    chosenColor = colors[temp%3]
    temp_counter  = 1
    nx.draw_networkx_nodes(G,circ_pos, nodelist=community , node_color=chosenColor , alpha=0.5)
  • Related