Combining Python’s Basemap and NetworkX

Recently I have been involved with a project mapping relationships between countries in terms of a social network. There are a lot of social network analysis packages around; I prefer Python’s NetworkX largely because I’m already so used to Python.

The first thing everyone wants to see when doing sna is the network graph…understandable of course as they look pretty visually attractive and are a welcome respite from a field (political science) which is dominated by text. However as we all know sna graphs can also be a bit misleading, unless you are very good at reading them. The fact that node position doesn’t (necessarily) mean anything is a bit of a disadvantage, and once you have more than a few nodes actually understanding link patterns is essentially impossible. Using a classic layout for my country relations SNA for example gives me this:

country-sna

Even with degree included as node size and colour I still don’t find it very informative. One way of improving the situation is to give some meaning to the node position, which is of course especially easy with countries. Displaying a sna as a world map has two advantages in my opinion: everyone knows the names of a lot of the countries (which saves you having to label nodes), and you can also get a quick handle on any geographical patterns.

Python’s Basemap module can be easily combined with NetworkX. The key is to build your NX graph’s ‘pos’ list as you are building your overall node list, using Basemap to transform node coordinates. Of course you will need a list of country longitudes and latitudes but there are plenty of those available.

Hence when I am building my overall graph, I do:

x,y = m(lon, lat)
G.add_node(country)
pos[country]=(x,y)

where m is any Basemap projection and lon, lat are the coordinates of the country in question.

country-sna-2

Much nicer.

2 Comments»

  Alireza wrote @

Thanks for the post. Do you have an example of this?
I’m trying to draw a graph with countries as nodes. Hence Every node can be shown on the location of the capital city of the country.
Is there any good dataset on the location of the capital cities?

  jonathanbright wrote @

There is a relatively complete list here which I have found useful in the past: http://www.csgnetwork.com/llinfotable.html

The example code is in the post :-)


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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: