使用Python-iGraph繪制貼吧/微博好友關系圖


想通過圖形化的方式顯示社交網絡特定用戶的好友關系,上網找了一下這方面的圖形庫有networkx、graphviz等,找了好久我選擇了iGraph這個圖形庫。

igraph在Windows下的安裝稍微有點麻煩,詳情參見:https://my.oschina.net/stu51/blog/335455

fans.txt 和 follow.txt分別保存了爬取下來的粉絲昵稱以及關注人昵稱。

#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)

 

最終結果如圖:

以上只演示了一個用戶的社交關系圖,有精力的話可以嘗試遞歸地一層一層爬下去,想象一下最終繪出來的圖也是挺炫酷的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM