Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting communities with python igraph

I have a graph g in python-igraph. I can get a VertexCluster community structure with the following:

community = g.community_multilevel()

community.membership gives me a list of the group membership of all the vertices in the graph.

My question is really simple but I haven't found a python-specific answer on SO. How can I plot the graph with visualization of its community structure? Preferably to PDF, so something like

layout = g.layout("kk")
plot(g, "graph.pdf", layout=layout) # Community detection?

Thanks a lot.

like image 219
jayelm Avatar asked Feb 24 '14 00:02

jayelm


2 Answers

Vertices remain ordered in the layout, graph, and VertexCluster, so you can do something like this:

Find the number of communities in the community structure:

>>> max(community.membership)
10

Then create a list/dictionary with max + 1 unique colors (probably not manually like below):

>>> color_list = [
...     'red',
...     'blue',
...     'green',
...     'cyan',
...     'pink',
...     'orange',
...     'grey',
...     'yellow',
...     'white',
...     'black',
...     'purple'
... ]

Then, using list comprehension, create a list containing the colors for each vertex based on the group membership of that vertex and assign that to vertex_color:

plot(g, "graph.png", layout=layout,
     vertex_color=[color_list[x] for x in community.membership])

Result (It's so pretty!)

graph

like image 52
jayelm Avatar answered Oct 07 '22 20:10

jayelm


A nice way to plot the communities could be the following using mark_groups:


Example:

from igraph import *
import random
random.seed(1)


g = Graph.Erdos_Renyi(30,0.3)
comms = g.community_multilevel()


plot(comms, mark_groups = True)

This results in the following:

enter image description here

Hope this helps.

like image 29
seralouk Avatar answered Oct 07 '22 19:10

seralouk