Jacob H
Jacob H

Reputation: 4513

Collapsing graph by clusters in igraph

I want to collapse a graph into its respective communities/clusters. Let me illustrate this with the following toy example:

set.seed(123)

#toy graph
g <- barabasi.game(10) %>%
  as.undirected()

#identify communities 
c_g <- fastgreedy.community(g) 

There are three communities, as seen in the following graph.

enter image description here

I want to reduce the collapse the vertices so that vertices in the resulting graph correspond to the membership of the previous vertices. See the graph.

enter image description here

I'm new to the igraph package and I'm not familiar with the best way of dealing with igraph objects.

Upvotes: 9

Views: 1185

Answers (1)

lukeA
lukeA

Reputation: 54287

You could try contract:

library(igraph)
set.seed(123)
g <- barabasi.game(10) %>% as.undirected()
c_g <- fastgreedy.community(g) 
V(g)$name <- letters[1:vcount(g)]

g2 <- contract(g, membership(c_g), vertex.attr.comb=toString)

par(mfrow=c(1,2))
plot(g, vertex.color=membership(c_g))
plot(simplify(g2), vertex.color=1:vcount(g2))

enter image description here

Upvotes: 11

Related Questions