创建基于图集的新图-R

时间:2018-11-20 13:44:12

标签: r igraph htmlwidgets networkd3

library("network")
library("networkD3")
library("igraph")

df1 <- read.table(text = "src   target
                  cllient1  cllient2
                  cllient1  cllient4
                  cllient1  cllient6
                  cllient2  cllient3
                  cllient4  cllient1
                  cllient4  cllient3
                  cllient5  cllient6
                  cllient6  cllient5", header = TRUE)

lesmis <- graph_from_data_frame(df1)
wc <- cluster_walktrap(lesmis)
members <- membership(wc)
lesmis <- igraph_to_networkD3(lesmis, group = members)

D3_network_LM <- networkD3::forceNetwork(Links = lesmis$links, Nodes = lesmis$nodes, 
                                         Source = 'source', Target = 'target', 
                                         NodeID = 'name', Group = 'group', 
                                         opacity = 1,zoom = TRUE)
networkD3::saveNetwork(D3_network_LM, "test.html", selfcontained = TRUE)

如此接近,我们有了一个网络。之后,我们通过将多个顶点合并为一个来创建新图。在我们的情况下,属于特定社区的那些顶点。

lesmis <- graph_from_data_frame(df1)
cg <- contract.vertices(lesmis, members)
ay <- as_long_data_frame(cg)
View(ay)

我们得到了新图

from    to
1   2

我们可能会再次构建新图,现在这些节点是组,但它们的名称分别是1和2,我的问题是我们如何才能向该新图添加客户端名称。这样,在悬停时,我们不仅可以获取节点(组)的编号,还可以获取属于该新节点(组)的客户端列表。

1 个答案:

答案 0 :(得分:0)

您的示例代码由于多种原因而无法正常工作(我对其进行了一些编辑以解决一些明显的问题),但是我认为以下实现了您要执行的操作...

library(network)
library(networkD3)
library(igraph)

df <- read.table(header = TRUE, 
                 text = "src   target
                         cllient1  cllient2
                         cllient1  cllient4
                         cllient1  cllient6
                         cllient2  cllient3
                         cllient4  cllient1
                         cllient4  cllient3
                         cllient5  cllient6
                         cllient6  cllient5")

df_graph <- graph_from_data_frame(df)

wc <- cluster_walktrap(df_graph)
members <- membership(wc)

df_graph_cntrctd <- contract(df_graph, members, vertex.attr.comb = toString)

df_graph_cntrctd_D3 <- igraph_to_networkD3(df_graph_cntrctd)

networkD3::forceNetwork(Links = df_graph_cntrctd_D3$links, 
                        Nodes = df_graph_cntrctd_D3$nodes, 
                        Source = 'source', Target = 'target', 
                        NodeID = 'name', Group = 'name', 
                        opacity = 1, zoom = TRUE)

enter image description here