如何为sankeyNetwork()定义节点和链接数据框

时间:2018-07-30 15:07:19

标签: r sankey-diagram htmlwidgets networkd3

我有一个从源国家/地区到目标国家/地区出口的文件,交易价值在Before_value维度中。 我的数据在data.table中,其中维度sourcetarget为字符(国家代码列表),数字为beofre_value

我想使用中的sankeyNetwork()来生成sankey图,其中源国家在左边,目标国家在右边,并表示流量。如何定义节点并正确链接数据帧? 我有以下几行:

library("networkD3")

sankeyNetwork(Links = IMP$source, Nodes = iMP$target, Source = "source",
              Target = "target", Value = "Before_value", fontSize = 25, 
              nodeWidth = 30, fontFamily = "sans-serif", iterations = 0)

我收到了他的错误消息:Error in Links[, Source] : incorrect number of dimensions

1 个答案:

答案 0 :(得分:0)

我相信您是在说sankeyNetwork()中的networkD3函数,而不是plotly包。假设是这种情况,这是一个最小的可重现示例,演示您的特定用例。

library(networkD3)

IMP <- data.frame(source = c("DEU", "DEU", "DEU", "FRA", "FRA", "FRA"),
                  target = c("ESP", "GBR", "ITA", "ESP", "GBR", "ITA"),
                  Before_value = c(4,2,7,4,1,8))

# create nodes data by determining all unique nodes found in your data
node_names <- unique(c(as.character(IMP$source), as.character(IMP$target)))
nodes <- data.frame(name = node_names)

# create links data by matching the source and target values to the index of the
# node it refers to in the nodes data frame
links <- data.frame(source = match(IMP$source, node_names) - 1,
                    target = match(IMP$target, node_names) - 1,
                    Before_value = IMP$Before_value)

sankeyNetwork(Links = links, Nodes = nodes, Source = "source", 
              Target = "target", Value = "Before_value")

enter image description here