(igraph) Grouped layout based on attribute

核能气质少年 提交于 2019-12-04 09:38:43

While this question is rather old, it is a reasonable question and deserves an answer.

No data was provided so I will generate an arbitrary example.

library(igraph)
set.seed(1234)
G = erdos.renyi.game(20, 0.25)
V(G)$Group1 = sample(3,20, replace=TRUE)
plot(G, vertex.color=rainbow(3, alpha=0.4)[V(G)$Group1])

Without doing anything, the Group is ignored.

Now, we need to create a layout that will plot nodes in the same group close together. We can do this by creating a graph with the same nodes, but with additional links between nodes in the same group. The within-group links will be given a high weight and the original links will be given a small weight. This will cluster nodes in the same group. We then apply the layout to plotting the original graph, without the extra links. They were just to get a good layout.

G_Grouped = G
E(G_Grouped)$weight = 1

## Add edges with high weight between all nodes in the same group
for(i in unique(V(G)$Group1)) {
    GroupV = which(V(G)$Group1 == i)
    G_Grouped = add_edges(G_Grouped, combn(GroupV, 2), attr=list(weight=5))
} 

## Now create a layout based on G_Grouped
set.seed(567)
LO = layout_with_fr(G_Grouped)

## Use the layout to plot the original graph
plot(G, vertex.color=rainbow(3, alpha=0.4)[V(G)$Group1], layout=LO)

If you want to go beyond this to have multiple levels of grouping, just add additional links with appropriate weights to connect the subgroups too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!