Social Network in Python Using NetworkX

14 Dec
My First Network Graph using NetworkX and Gephi.

My First Network Graph using NetworkX and Gephi.

I recently stumbled upon the PyData NYC 2012 Channel on Vimeo. This in turn led me to a talk by Gilad Lotan on NetworkX and Gephi. His talk is awesome, please check it out. I have played with NetworkX a little, mostly for a demonstration on Python and mapping I gave, so it was just an overview and I didn’t get to spend much time on it. After watching Gilad’s talk, I thought I would revisit NetworkX. I want to show a simple example of how to create a graph using NetworkX. I will save it as a PNG and a .GEXF to be edited in Gephi.

I hard coded a series of Nodes and Edges in my Python code. The nodes are the Names of people in the circles on the above image. The edges are the lines between them. I then used matplotlib to show the graph and to save it out as a .gexf. Here is the code:

import networkx as nx
import matplotlib.pyplot as plt

g=nx.Graph()

g.add_node(“Paul”)
g.add_node(“Joe”)
g.add_node(“Bill”)
g.add_node(“John”)
g.add_node(“Sarah”)
g.add_node(“Mary”)
g.add_node(“Karen”)
g.add_node(“Betsy”)
g.add_edge(“Betsy”,”Karen”)
g.add_edge(“Betsy”,”Paul”)
g.add_edge(“Betsy”,”Sarah”)
g.add_edge(“Paul”,”Sarah”)
g.add_edge(“Karen”,”Sarah”)
g.add_edge(“Sarah”,”Mary”)
g.add_edge(“Paul”,”Mary”)
g.add_edge(“Bill”,”Mary”)
g.add_edge(“John”,”Mary”)

nx.draw(g)
plt.savefig(“Something.png”)
nx.write_gexf(g, “Something.gexf”)

Import the libraries, create a graph, add nodes, add edges, then save. Simple. Now you can pull it in to Gephi and make it pretty- since this is the output I got from Matplot:

Output from Matplotlib - plt.show()

Output from Matplotlib – plt.show()


I won’t go in to detail on how to use Gephi – because honesty, I just used it for the first time – watch Gilad’s talk and learn from him – he knows what he’s doing!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: