February 9, 2010

Visualize your own twitter graph

Are you wondering how your twitter neighborhood looks like ? Here is a simple way to construct a “following” graph with python-graph, pygraphviz and twython. Don”t try this at home with a 10000+ nodes graph … this is a bad idea ! Also, the Twitter API clients only allow users to make a limited number of calls in a given hour. You can check your rate limit status with the following command: twitter.getRateLimitStatus().

UPDATE: This version  is better

# Import pygraph
from pygraph.classes.graph import graph
from pygraph.classes.digraph import digraph
from pygraph.algorithms.searching import breadth_first_search
from pygraph.readwrite.dot import write
 
# Import pygraphviz
from pygraphviz import *
 
# Import twython
import twython.core as twython
 
showFollowing = True
 
twitter = twython.setup(username="youraccount", password="yourpassword")
 
# List of users to graph
twitterUserListName = ['mlaprise', 'nside', 'annicklaprise', 'irina_sorokina']
 
# Get the list of followers/friends
if len(twitterUserListName) > 1:
	twitterUserList = []
	for i in range(len(twitterUserListName)):
		twitterUserList.append(
			twitter.showUser(screen_name=twitterUserListName[i])['id'])
else:
	twitterUser = twitter.showUser(screen_name=twitterUserListName[0])['id']
	twitterUserList = twitter.getFriendsIDs(id=twitterUser)
 
# Graph creation
twitterGraph = digraph()
 
for twitterUser in twitterUserList:
	if twitterUser not in twitterGraph.nodes():
		twitterGraph.add_node(twitterUser)
 
for twitterUser in twitterUserList:
 
	friendsList = twitter.getFriendsIDs(id=twitterUser)
	# Add Friends nodes from the user
	for friends in friendsList['ids']:
		if friends not in twitterGraph.nodes():
			twitterGraph.add_node(friends)
		if (friends, twitterUser) not in twitterGraph.edges():
			twitterGraph.add_edge([friends, twitterUser])
 
	if showFollowing:
		followersList = twitter.getFollowersIDs(id=twitterUser)
		# Add Following nodes from the user
		for followers in followersList:
			if followers not in twitterGraph.nodes():
				twitterGraph.add_node(followers)
			if (twitterUser, followers) not in twitterGraph.edges():
				twitterGraph.add_edge([twitterUser, followers])
 
# Construct the image of the graph
dot = write(twitterGraph)
twitterGraphViz = AGraph(string=dot)
 
twitterGraphViz.graph_attr['label']='Twitter Graph of mlaprise'
twitterGraphViz.graph_attr['dpi'] = '10'
twitterGraphViz.graph_attr['overlap'] = 'scale'
twitterGraphViz.node_attr['shape']='circle'
twitterGraphViz.node_attr['label']= ''
twitterGraphViz.node_attr['color']= 'blue'
twitterGraphViz.node_attr['style']= 'filled'
twitterGraphViz.edge_attr['color']='black'
twitterGraphViz.layout()
 
# Draw as PNG
twitterGraphViz.draw(str(twitterUserListName[0]) + '_graph.png')

Comments (1)

  1. June 11, 2010
    Hotmail Hacker said...

    Interesting post. Thanks.

Leave a Reply