删除sankey网络中的“未使用”节点

时间:2018-07-24 16:16:40

标签: r sankey-diagram networkd3

我正在尝试建立一个sankey网络。 这是我的数据和代码:

"element element1 element3".split(" ")

问题在于A和B仅具有指向D和E的公共链接。 尽管正确显示了链接,但D和E也显示在右下方。 如何避免这种情况? 注意:如果我指定

library(networkD3)
nodes <- data.frame(c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "D", "E", "N", "O", "P", "Q", "R"))
names(nodes) <- "name"
nodes$name = as.character(nodes$name)
links <- data.frame(matrix( 
  c(0,  2,  318.167, 
0,  3,  73.85, 
0,  4,  51.1262,
0,  5,  6.83333,
0,  6,  5.68571,
0,  7,  27.4167,
0,  8,  4.16667,
0,  9,  27.7381,
1,  10, 627.015,
1,  3,  884.428,
1,  4,  364.211,
1,  13, 12.33333,
1,  14, 9,
1,  15, 37.2833,
1,  16, 9.6,
1,  17, 30.5485), nrow=16, ncol=3, byrow = TRUE))
colnames(links) <- c("source", "target", "value")
links$source = as.integer(links$source)
links$target = as.integer(links$target)
links$value = as.numeric(links$value)
sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
          Target = "target", Value = "value", NodeID = "name",
          fontSize = 12, fontFamily = 'Arial', nodeWidth = 20)

根本没有创建网络。

enter image description here

1 个答案:

答案 0 :(得分:2)

节点必须唯一,请参见以下示例。我删除了重复的节点:“ D”和“ E”,然后在链接中,删除了引用不存在的节点的链接。我们只有16个节点,从零开始的0:15。在链接 dataframe 中,您有最后两行分别引用16和17。


或作为@CJYetman (networkD3 author)条评论:

  

另一种说法...将绘制节点数据框中的每个节点,即使它的名称与另一个节点相同,因为从技术上讲索引是唯一的ID。

library(networkD3)

nodes <- data.frame(name = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "N", "O", "P", "Q", "R"), 
                    ix = 0:15)

links <- data.frame(matrix( 
  c(0,  2,  318.167, 
    0,  3,  73.85, 
    0,  4,  51.1262,
    0,  5,  6.83333,
    0,  6,  5.68571,
    0,  7,  27.4167,
    0,  8,  4.16667,
    0,  9,  27.7381,
    1,  10, 627.015,
    1,  3,  884.428,
    1,  4,  364.211,
    1,  13, 12.33333,
    1,  14, 9,
    1,  15, 37.2833), nrow=14, ncol=3, byrow = TRUE))
colnames(links) <- c("source", "target", "value")

sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              fontSize = 12, fontFamily = 'Arial', nodeWidth = 20)

enter image description here