Color cluster members in a network

Viewed 70

I would like to use membership() as palette index to colour a network nodes according to the one to which they belong. I compute clusters on a subset of an igraph object. I wish to color only the element of the subgraph and leave the rest grey.

I found a way to do that for small networks, by hand but cannot find a way to do it automatically.

If I use the method discussed here, it breaks.

library("igraph")
library("igraphdata")

data(karate)
V(karate)$name <- gsub("ctor ","",V(karate)$name)

karate_1 <- induced.subgraph(karate, vids=which(graph.coreness(karate) > 2))
clu <- cluster_louvain(karate_1)
membership(clu)
V(karate)$color <- ifelse(V(karate)$name %in% c("Mr Hi","A2","A3","A4","A8","A14","A20"), "green",
                          ifelse(V(karate)$name %in% c("A5","A6","A7","A11"), "red",
                                 ifelse(V(karate)$name %in% c("A9","A24","A25","A26","A28","A29","A30","A31","A32","A33","John A"), "blue","grey50")))

plot(karate, mark.groups=communities(clu), vertex.label=NA,edge.color = "grey50")
1 Answers

Try the following. In order to make the code more clear I create a vector of colors but that is not strictly necessary.

  1. Create a logical index of the vertices names that exist in membership(clu);
  2. Assign the default color "grey50" to all vertices;
  3. Assign the cluster colors to their respective vertices using the logical index and the membership number.

And plot the graph.

clrs <- c("red", "green", "blue")
i <- V(karate)$name %in% names(membership(clu))
V(karate)$color <- "grey50"
V(karate)$color[i] <- clrs[membership(clu)]
plot(karate, mark.groups=communities(clu), vertex.label=NA,edge.color = "grey50")

enter image description here

Related