可视化igraph作为R中的内外圆

时间:2016-07-20 21:13:26

标签: r layout igraph

我使用以下代码生成圆形布局格式的visNetwork(下面附有图片)

visNetwork(data$nodes,data$edges) %>% visIgraphLayout(layout="layout_in_circle")

我希望以这样的方式更改布局:内圈中的绿色节点和外圈中的蓝色节点。请告诉我如何实现这一目标。

提前致谢。 Image Link

1 个答案:

答案 0 :(得分:2)

一种方法是在igraph中构建布局。您可以在最后将其反馈到visNetwork。我不确定你是否想让内圈连接到外圈。这两个选项都已编码。

调用绿色节点nodes1和蓝色节点nodes2,通过对节点矩阵进行子集化来创建。

# edges within nodes1
edges1 <- edges[edges$from%in%nodes1$id & edges$to%in%nodes1$id, ] 
# edges within nodes2 
edges2 <- edges[edges$from%in%nodes2$id & edges$to%in%nodes2$id, ]
# edges within nodes1 or 2 = all edges if nodes1, 2 account for all nodes
edges12 <-edges[edges$from%in%c(nodes2$id,nodes1$id) &
  edges$to%in%c(nodes2$id,nodes1$id) , ]

igraph1 <- graph.data.frame(edges1, directed=F, vertices=nodes1)
igraph2 <- graph.data.frame(edges2, directed=F, vertices=nodes2)

# inner circle doesn't connect to outer:
igraph12a <- graph.data.frame(rbind(edges1, edges2), directed = F,
  vertices = rbind(nodes1, nodes2))

# inner circle can connect to outer:
igraph12b <- graph.data.frame(edges12, directed = F, vertices =
  rbind(nodes1, nodes2))

l1 = layout.circle(igraph1)
l2 = layout.circle(igraph2)
l12 = rbind(l1, l2 * 0.5) # 0.5 term scales the inner circle size

# plot both circles
plot.igraph(igraph1, layout = l1, rescale = F)
plot.igraph(igraph2, layout = l2*.5, add = T, rescale = F)

# plot both circles at once
plot.igraph(igraph12a, layout = l12, rescale = F)

# plot both circles with possible connections between them
plot.igraph(igraph12b, layout = l12, rescale = F)

然后,如果你喜欢它在visNetwork中,你可以做到这一点。确保你有一个更新版本的visNetwork,因为带有layoutMatrix功能的layout.norm是最近添加的:

visNetwork(nodes = rbind(nodes1, nodes2), edges = edges12) %>% 
  visIgraphLayout(layout="layout.norm", layoutMatrix = l12)  

当然,您需要为所有这些添加节点颜色。