我试图找出forceNetwork()中节点和链接数据框架的确切要求,因为我的网络显示彩色可移动点,没有任何边缘连接它们,我不知道为什么。据我所知,这些要求是:
节点数据帧必须有:
链接数据帧必须有:
> head(links)
source target value
1 11170 7 1
2 2840 2 1
3 32595 2 1
4 45410 8 1
5 52720 12 1
6 61720 6 1
> head(nodes)
nodeID group
1 11170 2
2 2840 1
3 32595 2
4 45410 3
5 52720 1
6 61720 2
> head(E(g))
Edge sequence:
[1] 7 -- 11170
[2] 2 -- 2840
[3] 2 -- 32595
[4] 8 -- 45410
[5] 12 -- 52720
[6] 6 -- 61720
> head(V(g))
Vertex sequence:
[1] "11170" "2840" "32595" "45410" "52720" "61720"
> typeof(nodes$nodeID[1])
[1] "integer"
> typeof(links$source[1])
[1] "integer"
> dim(links)
[1] 121 3
> dim(nodes)
[1] 135 2
> forceNetwork(Links = links, Nodes = nodes,Source = "source", Target = "target", NodeID = "nodeID",Group = "group", opacity = 0.8, colourScale = "d3.scale.category10()")
Links
数据帧中的source
和 target
向量必须是数字,它们的值指的是它们所代表的Nodes
数据帧中节点的索引(零索引,不像R,因为它被JavaScript代码使用)。
Nodes
数据帧的nodeID
向量给出了每个节点的名称(字符或数字),当您将鼠标悬停在结果可视化中的节点上时,将显示该名称。
给定您的示例数据,我怀疑您在links$source
中拥有的数据意味着节点的ID,而您在links$target
中拥有的数据是其他东西。虽然它们都是数值向量,但这些值并不表示它们在Nodes
数据帧中所引用的节点的索引。
如果你在links$source
和links$target
向量中有节点名称/id,而不是在Nodes
数据框架中节点的索引,你可以像这样修复它…
links <- read.table(header = T, text = "
source target value
11170 7 1
2840 2 1
32595 2 1
45410 8 1
52720 12 1
61720 6 1
")
nodes <- read.table(header = T, text = "
nodeID group
11170 2
2840 1
32595 2
45410 3
52720 1
61720 2
")
# build a new Nodes data frame that includes every
# unique node found in links$source and links$target
nodes_complete <- data.frame(nodeID = unique(c(links$source, links$target)))
# add groups already identified in your original Nodes data frame
nodes_complete$group <- nodes$group[match(nodes_complete$nodeID, nodes$nodeID)]
# convert your links$source and links$target nodes to their index
# in the new Nodes data frame (zero-indexed)
links$source <- match(links$source, nodes_complete$nodeID) - 1
links$target <- match(links$target, nodes_complete$nodeID) - 1
# now the forceNetwork function will run as expected
library(networkD3)
forceNetwork(Links = links, Nodes = nodes_complete, Source = "source",
Target = "target", NodeID = "nodeID", Group = "group",
opacity = 0.8,
colourScale = "d3.scaleOrdinal(d3.schemeCategory10);")