簡體   English   中英

Networkx - 從社區創建圖表

[英]Networkx - create graphs from communities

使用以下工作代碼:

import netowkx as nx
import networkx.algorithms.community as nx_comm

G = nx.karate_club_graph()

# Find the communities
communities = sorted(nx_comm.greedy_modularity_communities(G), key=len, reverse=True)
# Count the communities
print(f"The club has {len(communities)} communities.")

'''Add community to node attributes'''
for c, v_c in enumerate(communities):
    for v in v_c:
        # Add 1 to save 0 for external edges
        G.nodes[v]['community'] = c + 1
        

'''Find internal edges and add their community to their attributes'''
for v, w, in G.edges:
    if G.nodes[v]['community'] == G.nodes[w]['community']:
        # Internal edge, mark with community
        G.edges[v, w]['community'] = G.nodes[v]['community']
    else:
        # External edge, mark as 0
        G.edges[v, w]['community'] = 0

如何為每個社區獲得n新圖(或子圖)、一個 object(描述為“具有 n 個節點和 w 邊的圖”)?

您可以使用與本文采用的方法類似的方法來做您想做的事情。 首先,您可以為每個社區創建一個圖表。 然后,您可以使用[(u,v,d) for u,v,d in G.edges(data=True) if d['community'] == i+1])來識別要添加到每個圖中的邊[(u,v,d) for u,v,d in G.edges(data=True) if d['community'] == i+1]) .

這是代碼的樣子:

import networkx as nx
import networkx.algorithms.community as nx_comm
import matplotlib.pyplot as plt

G = nx.karate_club_graph()

# Find the communities
communities = sorted(nx_comm.greedy_modularity_communities(G), key=len, reverse=True)

# Count the communities
print(f"The club has {len(communities)} communities.")

'''Add community to node attributes'''
for c, v_c in enumerate(communities):
    for v in v_c:
        # Add 1 to save 0 for external edges
        G.nodes[v]['community'] = c + 1

'''Find internal edges and add their community to their attributes'''
for v, w, in G.edges:
    if G.nodes[v]['community'] == G.nodes[w]['community']:
        # Internal edge, mark with community
        G.edges[v, w]['community'] = G.nodes[v]['community']
    else:
        # External edge, mark as 0
        G.edges[v, w]['community'] = 0



N_coms=len(communities)
edges_coms=[]#edge list for each community
coms_G=[nx.Graph() for _ in range(N_coms)] #community graphs
colors=['tab:blue','tab:orange','tab:green']
fig=plt.figure(figsize=(12,5))

for i in range(N_coms):
  edges_coms.append([(u,v,d) for u,v,d in G.edges(data=True) if d['community'] == i+1])#identify edges of interest using the edge attribute
  coms_G[i].add_edges_from(edges_coms[i]) #add edges
  plt.subplot(1,3,i+1)#plot communities
  plt.title('Community '+str(i+1))
  pos = nx.circular_layout(coms_G[i])
  nx.draw(coms_G[i],pos=pos,with_labels=True,node_color=colors[i]) 

output 給出:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM