i'm working on script visualize communities in large network. i'd select edges in graph based on community membership of nodes, , change color attributes.
for example, can construct graph , give nodes unique names this:
library(igraph) library(random) g <- barabasi.game(100) v(g)$name <- randomstrings(100,len=2,digits=false,loweralpha=false) wt <- walktrap.community(g)
then choose 1 community visualize , create induced subgraph:
v3 <- v(g)[membership(wt)==3] g3 <- induced.subgraph(g,v3)
the best way i've found matching edges this:
matching_edge <- function(g1,e,g2) { # given edge e in g1, return corresponding edge in g2 name1 <- v(g1)[get.edges(g1,e)[1,1]]$name name2 <- v(g1)[get.edges(g1,e)[1,2]]$name e(g2)[get.edge.ids(g2,c(name1,name2))] } e(g)$color = 'gray' (e in e(g3)) { eg <- matching_edge(g3,e,g) e(g)[eg]$color <- 'red' }
and finally, plot:
plot(g, vertex.label=na, vertex.shape="none", vertex.size=0, edge.arrow.mode=0, edge.width=1)
this works right, loop matching_edge()
gets painfully slow large-ish graphs of few thousand nodes. seems there should better way this, i'm @ loss is.
any ideas?
you not need produce subgraph this.
constructing graph:
library(igraph) g <- barabasi.game(100) wt <- walktrap.community(g)
making array of colours , assigning edges based on community of source node:
linkcolors<-rainbow(max(wt$membership)) e(g)$color <- linkcolors[membership(wt)[tail_of(g,e(g))]]
plot:
plot(g, vertex.label=na, vertex.shape="none", vertex.size=0, edge.arrow.mode=0, edge.width=1)
here's longer, step step version of solution:
# largest membership id equals number of communities numberofcommunities<- max(wt$membership) # array of many colours there communities linkcolors<-rainbow(numberofcommunities) # array source vertex of each edge sourcenodes<-tail_of(g,e(g)) # array community of source vertex of each edge linkmemberships<- membership(wt)[sourcenodes] # array colours corresponding # community of source vertex of each edge linkcolors <- linkcolors[linkmemberships] e(g)$color <- linkcolors
if want use community of target node instead, use head_of() instead of tail_of().
to colour edges source , target node in same community , treat edges between communities differently (for example undirected graphs), add before plotting:
# edges between communities: between_communities_edges<-which(membership(wt)[tail_of(g,e(g))]!=membership(wt)[head_of(g,e(g))]) # them: e(g)[between_communities_edges]$color='grey95'