前言
最近工作中遇到了一些需求,想通过图形化的方式显示社交网络特定用户的好友关系,上网找了一下这方面的图形库有networkx、graphviz等,找了好久我选择了iGraph这个图形库。下面话不多说了,来一起看看详细的介绍吧。
安装igraph
igraph在Windows下的安装稍微有点麻烦,之前尝试在windows用pip和conda直接装igraph都装不上,后来发现了lfd的网站 Unofficial Windows Binaries for Python Extension Packages , 里面有很多python的资源和库与工具。
在上面的网址中找到python_igraph去下载具体的python对应版本和是32位还是64位的,比如我下载了 python_igraph‑0.7.1.post6‑cp35‑none‑win_amd64.whl
利用pip 安装whl文件:pip install 文件名.whl
为了避免出错,打开cmd以后,要cd进入你存放的该whl文件的解压后的目录下在用pip进行安装。
绘制好友关系图
fans.txt 和 follow.txt分别保存了爬取下来的粉丝昵称以及关注人昵称。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#coding=utf-8 from igraph import * count_fans = 0 #粉丝数 count_following = 0 #关注人数 fans_name = [] #粉丝昵称 following = [] #关注人昵称 #打开爬取下的昵称文件 with open ( 'fans.txt' , 'r' ) as f: lines = f.readlines() for line in lines: if (line! = None )&(line! = '\n' ): fans_name.append(line) # print fans_name count_fans + = 1 with open ( 'follow.txt' , 'r' ) as c: lines = c.readlines() for line in lines: if (line! = None )&(line! = '\n' ): following.append(line) count_following + = 1 g = Graph() #创建 g.add_vertices( 3 + count_fans + count_following) g.add_edges([( 0 , 1 ),( 1 , 2 )]) g.vs[ 0 ][ "name" ] = 'Ta的粉丝' g.vs[ 1 ][ "name" ] = '目标用户' g.vs[ 2 ][ "name" ] = 'Ta的关注' g.es[ "trunk" ] = [ True , True ] g.vs[ "main_node" ] = [ 1.5 , 3 , 1.5 ] for i in range ( 3 ,count_fans + 3 ): g.add_edges(( 0 ,i)) g.es[i - 1 ][ "trunk" ] = False for j in range (count_fans + 3 , 3 + count_fans + count_following): g.add_edges(( 2 ,j)) g.es[j - 1 ][ "trunk" ] = False index = 3 for fans in fans_name: g.vs[index][ "name" ] = fans g.vs[index][ "main_node" ] = False index + = 1 for name in following: g.vs[index][ "name" ] = name g.vs[index][ "main_node" ] = False index + = 1 visual_style = {} color_dic = { 1.5 : "#cfe6ff" , 3 : "#7299a7" , False : "#cfe6ff" } visual_style[ "vertex_label_size" ] = 11 visual_style[ "vertex_label_dist" ] = 1 visual_style[ "vertex_shape" ] = "circle" visual_style[ "vertex_size" ] = [ 7 + 10 * int (main_node) for main_node in g.vs[ "main_node" ]] visual_style[ "edge_width" ] = [ 1 + 2 * int (trunk) for trunk in g.es[ "trunk" ]] visual_style[ "vertex_color" ] = [color_dic[main_node] for main_node in g.vs[ "main_node" ]] visual_style[ "vertex_label" ] = g.vs[ "name" ] visual_style[ "bbox" ] = ( 1000 , 1000 ) visual_style[ "margin" ] = 150 layout = g.layout( "grid_fr" ) visual_style[ "layout" ] = layout plot(g, * * visual_style) |
最终结果如图:
以上只演示了一个用户的社交关系图,有精力的话可以尝试递归地一层一层爬下去,想象一下最终绘出来的图也是挺炫酷的。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:http://www.cnblogs.com/lovealways/p/6653006.html