如何为 sankeyNetwork() 定义节点和链接数据框
how to define nodes and links data frame for sankeyNetwork()
我有一个从源国家出口到目标国家的文件,贸易价值在 Before_value 维度。
我的数据在 data.table 中,尺寸为 source
和 target
作为字符(国家代码列表)和 beofre_value
数字。
我想使用 networkd3 中的 sankeyNetwork()
生成一个桑基图,左边是源国家,右边是目标国家,并表示流量。如何正确定义节点和链接数据框?
我有这些行:
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
我相信您是在谈论 networkD3
中的 sankeyNetwork()
函数,而不是 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")
我有一个从源国家出口到目标国家的文件,贸易价值在 Before_value 维度。
我的数据在 data.table 中,尺寸为 source
和 target
作为字符(国家代码列表)和 beofre_value
数字。
我想使用 networkd3 中的 sankeyNetwork()
生成一个桑基图,左边是源国家,右边是目标国家,并表示流量。如何正确定义节点和链接数据框?
我有这些行:
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
我相信您是在谈论 networkD3
中的 sankeyNetwork()
函数,而不是 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")