python网络

 1 import community
 2 import networkx as nx
 3 import matplotlib.pyplot as plt
 4 
 5 #better with karate_graph() as defined in networkx example.
 6 #erdos renyi don't have true community structure
 7 G = nx.erdos_renyi_graph(30, 0.05)
 8 
 9 #first compute the best partition
10 partition = community.best_partition(G)
11 
12 #drawing
13 size = float(len(set(partition.values())))
14 pos = nx.spring_layout(G)
15 count = 0.
16 for com in set(partition.values()) :
17     count = count + 1.
18     list_nodes = [nodes for nodes in partition.keys()
19                                 if partition[nodes] == com]
20     nx.draw_networkx_nodes(G, pos, list_nodes, node_size = 20,
21                                 node_color = str(count / size))
22 
23 
24 nx.draw_networkx_edges(G,pos, alpha=0.5)
25 plt.show()

首先一定要先安装好这三个库,community,networkx,matplotlib,这个很简单使用pip install就好。

但是在运行的过程中可能会出现这种错误“module 'community' has no attribute 'best_partition'。”

原因是缺少python-louvain.

再pip 安装就好。

结果如下图所示。

 

 

posted @ 2018-12-29 17:27  又名王十二  阅读(1253)  评论(0编辑  收藏  举报