我有一个从源国家/地区到目标国家/地区出口的文件,交易价值在Before_value维度中。
我的数据在data.table中,其中维度source
和target
为字符(国家代码列表),数字为beofre_value
。
我想使用networkd3中的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
答案 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")