How to make grouped layout in igraph?

deeenes picture deeenes · May 6, 2013 · Viewed 10.5k times · Source

In igraph, after applying a modularization algorithm to find graph communites, i would like to draw a network layout which clearly makes visible the distinct communities and their connections. Something like "group attributes layout" in Cytoscape: i want to show the members of each group/community close to each other, and keep some distance between groups/communities. I couldn't find any function in igraph providing this feature out of the box. While posting this question i have already found out a simple d.i.y solution, i going to post it as an answer. But i am wondering if there is any better possibility, or more elaborated solution?

Answer

Antoine picture Antoine · Mar 17, 2015

To expand on Gabor's suggestion, I have created this function:

weight.community=function(row,membership,weigth.within,weight.between){
if(as.numeric(membership[which(names(membership)==row[1])])==as.numeric(membership[which(names(membership)==row[2])])){
weight=weigth.within
}else{
weight=weight.between
}
return(weight)
}

Simply apply it over the rows of the matrix of edges of your graph (given by get.edgelist(your_graph)) to set the new edge weights (membership is the membership vector from the result of any community detection algorithm):

E(g)$weight=apply(get.edgelist(g),1,weight.community,membership,10,1)

Then, simply use a layout algorithm that accepts edge weights such as the fruchterman.reingold as suggested by Gabor. You can tweak the weights arguments to obtain the graph you want. For instance:

E(g)$weight=apply(get.edgelist(g),1,weight.community,membership,10,1)
g$layout=layout.fruchterman.reingold(g,weights=E(g)$weight)
plot(g)

enter image description here

E(g)$weight=apply(get.edgelist(g),1,weight.community,membership,1000,1)
g$layout=layout.fruchterman.reingold(g,weights=E(g)$weight)
plot(g)

enter image description here

Note 1: the transparency/colors of the edges are other parameters of my graphs. I have colored nodes by community to shows that it indeed works.

Note 2: make sure to use membership(comm) and not comm$membership, where comm is the result of the community detection algorithm (e.g., comm=leading.eigenvector.community(g)). The reason is that in the first case, you get a numeric vector with names (what we want), and in the second case, the same vector without names.

To get consensus of multiple community detection algorithms, see this function.