python画关系网图_使用python绘制人人网好友关系图示例

代码依赖:networkx matplotlib

#! /bin/env python

# -*- coding: utf-8 -*-

import urllib

import urllib2

import cookielib

import re

import cPickle as p

import networkx as nx

import matplotlib.pyplot as plt

__author__ = """Reverland (lhtlyy@gmail.com)"""

# Control parameters,EDIT it here

## Login

username = 'None'

password = 'None'

## Control Graphs, Edit for better graphs as you need

label_flag = True # Whether shows labels.NOTE: configure your matplotlibrc for Chinese characters.

remove_isolated = True # Whether remove isolated nodes(less than iso_level connects)

different_size = True # Nodes for different size, bigger means more shared friends

iso_level = 10

node_size = 40 # Default node size

def login(username, password):

"""log in and return uid"""

logpage = "http://www.renren.com/ajaxLogin/login"

data = {'email': username, 'password': password}

login_data = urllib.urlencode(data)

cj = cookielib.CookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

urllib2.install_opener(opener)

res = opener.open(logpage, login_data)

print "Login now ..."

html = res.read()

#print html

# Get uid

print "Getting user id of you now"

res = urllib2.urlopen("http://www.renren.com/home")

html = res.read()

# print html

uid = re.search("'ruid':'(\\d+)'", html).group(1)

# print uid

print "Login and got uid successfully"

return uid

def getfriends(uid):

"""Get the uid's friends and return the dict with uid as key,name as value."""

print "Get %s 's friend list" % str(uid)

pagenum = 0

dict1 = {}

while True:

targetpage = "http://friend.renren.com/GetFriendList.do?curpage=" + str(pagenum) + "&id=" + str(uid)

res = urllib2.urlopen(targetpage)

html = res.read()

pattern = '[\\S]*[\\s]\\((.*)\\)'

m = re.findall(pattern, html)

#print len(m)

if len(m) == 0:

break

for i in range(0, len(m)):

no = m[i][0]

uname = m[i][1]

#print uname, no

dict1[no] = uname

pagenum += 1

print "Got %s 's friends list successfully." % str(uid)

return dict1

def getdict(uid):

"""cache dict of uid in the disk."""

try:

with open(str(uid) + '.txt', 'r') as f:

dict_uid = p.load(f)

except:

with open(str(uid) + '.txt', 'w') as f:

p.dump(getfriends(uid), f)

dict_uid = getdict(uid)

return dict_uid

def getrelations(uid1, uid2):

"""receive two user id, If they are friends, return 1, otherwise 0."""

dict_uid1 = getdict(uid1)

if uid2 in dict_uid1:

return 1

else:

return 0

def getgraph(username, password):

"""Get the Graph Object and return it.

You must specify a Chinese font such as `SimHei` in ~/.matplotlib/matplotlibrc"""

uid = login(username, password)

dict_root = getdict(uid) # Get root tree

G = nx.Graph() # Create a Graph object

for uid1, uname1 in dict_root.items():

# Encode Chinese characters for matplotlib **IMPORTANT**

# if you want to draw Chinese labels,

uname1 = unicode(uname1, 'utf8')

G.add_node(uname1)

for uid2, uname2 in dict_root.items():

uname2 = unicode(uname2, 'utf8')

# Not necessary for networkx

if uid2 == uid1:

continue

if getrelations(uid1, uid2):

G.add_edge(uname1, uname2)

return G

def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):

"""Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net"""

print "Generating graph..."

try:

with open(filename, 'r') as f:

G = p.load(f)

except:

G = getgraph(username, password)

with open(filename, 'w') as f:

p.dump(G, f)

#nx.draw(G)

# Judge whether remove the isolated point from graph

if remove_isolated is True:

H = nx.empty_graph()

for SG in nx.connected_component_subgraphs(G):

if SG.number_of_nodes() > iso_level:

H = nx.union(SG, H)

G = H

# Ajust graph for better presentation

if different_size is True:

L = nx.degree(G)

G.dot_size = {}

for k, v in L.items():

G.dot_size[k] = v

node_size = [G.dot_size[v] * 10 for v in G]

pos = nx.spring_layout(G, iterations=50)

nx.draw_networkx_edges(G, pos, alpha=0.2)

nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3)

# Judge whether shows label

if label_flag is True:

nx.draw_networkx_labels(G, pos, alpha=0.5)

#nx.draw_graphviz(G)

plt.show()

return G

if __name__ == "__main__":

G = draw_graph(username, password)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Python和igraph库绘制贴吧或微博的好友关系,可以按照以下步骤进行: 1. 安装igraph库:在Python环境下使用命令`pip install python-igraph`来安装igraph库。 2. 准备数据:首先需要获取好友关系的数据。可以通过贴吧或微博提供的API接口获取好友列表或关注列表,并将这些数据保存为适当的格式,如CSV或JSON。数据应包括每个用户的唯一标识符和其关联的好友的唯一标识符。 3. 加载数据:使用igraph库的方法来加载数据。可以使用`Graph.TupleList`方法将关系列表转换为对象。可以使用类似以下代码的方式加载数据: ```python from igraph import Graph edges = [(1, 2), (1, 3), (2, 3)] # 示例关系列表 g = Graph.TupleList(edges, directed=False) ``` 这将创建一个无向对象g,其中包含了关系列表中的节点和边。 4. 设置的布局:使用igraph库提供的布局算法来确定节点在中的位置。可以选择使用`layout_fruchterman_reingold`或`layout_kamada_kawai`等布局算法。例如,可以使用以下代码设置的布局: ```python layout = g.layout_fruchterman_reingold() ``` 5. 绘制使用igraph库的绘函数将绘制出来。例如,可以使用以下代码将绘制为PNG像: ```python from igraph import plot plot(g, layout=layout, bbox=(800, 800), vertex_size=20, vertex_color='red', edge_width=1, edge_color='gray', margin=50).save('friend_graph.png') ``` 这将创建一个名为`friend_graph.png`的PNG像文件,其中包含了好友关系。 可以根据需求自定义的外观和样式,设置节点和边的颜色、大小、边缘、标签等。 总之,使用Python和igraph库,可以很方便地绘制贴吧或微博的好友关系。关键步骤包括准备数据、加载数据、设置的布局和样式、绘制像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值