Reputation: 57
I have created a graph and used the propagating labels community detection algorithm to detect subgroups in the graph. I have then plotted the graph and coloured the vertices according to their group membership using rainbow colours. Here is the code I used:
g <- watts.strogatz.game(1, 100, 5, 0.05)
clp <- cluster_label_prop(g)
V(g)$community <- clp$membership
rain <- rainbow(14, alpha=.5)
V(g)$color <- rain[V(g)$community]
plot(g, vertex.size=4, vertex.label=NA)
I would now like to colour edges that lie between members of a subgroup in the same colour as that subgroup, in order to better highlight the within-group ties. I would like to leave the between-group ties grey. I cannot work out how to do it, help would be greatly appreciated.
Thanks
Upvotes: 2
Views: 2525
Reputation: 666
A solution with map() from the purrr-package would be:
library(igraph)
library(ggraph)
library(purrr)
g <- watts.strogatz.game(1, 100, 5, 0.05)
clp <- cluster_label_prop(g)
V(g)$color <- clp$membership
a1 <- as.data.frame(get.edgelist(g))
E(g)$color <- map2_dbl(a1$V1, a1$V2, ~ {
ifelse(
V(g)$color[V(g)[.x]] ==
V(g)$color[V(g)[.y]],
V(g)$color[V(g)[.x]],
9999)
})
and then visualising with ggraph:
ggraph(g, layout='fr') +
geom_edge_link0(aes(color=as.factor(color)), width=0.6, alpha=0.35) +
geom_node_point(aes(color=as.factor(color)), size=3, alpha=0.75) +
theme_graph(base_family = 'Helvetica')
... or making difference between within-community-edges and other edges very distinct:
ggraph(g, layout='fr') +
geom_edge_link0(aes(filter=color!=9999 ,color=as.factor(color)), width=0.6, alpha=0.35) +
geom_edge_link0(aes(filter=color==9999), color='grey', width=0.5, alpha=0.25) +
geom_node_point(aes(color=as.factor(color)), size=3, alpha=0.75) +
theme_graph(base_family = 'Helvetica')
Upvotes: 1
Reputation: 23101
The following should work:
library(igraph)
g <- watts.strogatz.game(1, 100, 5, 0.05)
clp <- cluster_label_prop(g)
V(g)$community <- clp$membership
rain <- rainbow(14, alpha=.5)
V(g)$color <- rain[V(g)$community]
E(g)$color <- apply(as.data.frame(get.edgelist(g)), 1,
function(x) ifelse(V(g)$community[x[1]] == V(g)$community[x[2]],
rain[V(g)$community[x[1]]], '#00000000'))
plot(g, vertex.size=4, vertex.label=NA, edge.color=E(g)$color)
Upvotes: 2