受 Antoine 的建议启发,我创建了这个函数:
edge.weights <- function(community, network, weight.within = 100, weight.between = 1) {
bridges <- crossing(communities = community, graph = network)
weights <- ifelse(test = bridges, yes = weight.between, no = weight.within)
return(weights)
}
函数也是如此;只需将您的社区对象放在社区插槽中,您的图形在网络中。我会离开 weight.between = 1 并调整 weight.within 值。
然后将权重转移到节点中的weight槽:
E(graph)$weight <- edge.weights(community, graph)
最后使用一种使用权重的布局算法,例如layout_with_fr(igraph 1.0.1 中fruchterman.reingold 的新名称)。
我以 Zachary 的空手道俱乐部网络为例。
library(igraph)
library(igraphdata)
#I load the network
data(karate)
#for reproducible purposes
set.seed(23548723)
karateLayout <- layout_with_fr(karate)
par(mar = c(0,0,2,0))
plot(karate, vertex.size = 10, vertex.color = "steelblue4", edge.width = 1,
vertex.label = NA, edge.color = "darkgrey", layout = karateLayout,
main = "Zachary's karate club network" )
我通过 cluster_louvain 函数对模块化进行多级优化来检测社区:
Communitykarate <- cluster_louvain(karate)
接下来是个人偏好而不是默认设置:
prettyColors <- c("turquoise4", "azure4", "olivedrab","deeppink4")
communityColors <- prettyColors[membership(Communitykarate)]
用颜色突出显示社区的图表是:
plot(x = Communitykarate, y = karate, edge.width = 1, vertex.size = 10,
vertex.label = NA, mark.groups = NULL, layout = karateLayout, col = communityColors,
main = "Communities in Zachary's karate club network",
edge.color = c("darkgrey","tomato2")crossing(Communitykarate, karate) + 1])
现在,这个问题存在的意义。
E(karate)$weight <- edge.weights(Communitykarate, karate)
# I use the original layout as a base for the new one
karateLayoutA <- layout_with_fr(karate, karateLayout)
# the graph with the nodes grouped
plot(x = Communitykarate, y = karate, edge.width = 1, vertex.size = 10,
mark.groups = NULL, layout = karateLayoutA, vertex.label = NA, col = communityColors,
c("darkgrey","tomato2")[crossing(Communitykarate, karate) + 1],
main = "Communities in Zachary's karate club network (grouped)")
如果您尝试增加体重,您将拥有:
E(karate)$weight <- edge.weights(Communitykarate, karate, weight.within = 1000)
karateLayoutB <- layout_with_fr(karate, karateLayout)
plot(x = Communitykarate, y = karate, edge.width = 1, vertex.size = 10,
mark.groups = NULL, layout = karateLayoutB, vertex.label = NA, col = communityColors,
c("darkgrey","tomato2")[crossing(Communitykarate, karate) + 1],
main = "Communities in Zachary's karate club network (grouped)")