如何为sankeyNetwork()定义节点和链接数据框 [英] how to define nodes and links data frame for sankeyNetwork()
问题描述
我有一个从源国家/地区到目标国家/地区出口的文件,贸易价值在Before_value维度中.
我的数据在data.table中,其中尺寸source
和target
为字符(国家代码列表)和beofre_value
数字.
I have a file with export from source country to target country, the value of the trade is in Before_value dimension.
My data is in a data.table with dimensions source
and target
as character (list of country codes) and beofre_value
numeric.
我想使用sankeyNetwork()来生成sankey图>网络3 ,左侧是来源国,右侧是目标国,代表流量.如何定义节点并正确链接数据帧? 我有以下几行:
I would like to generate a sankey diagram, using sankeyNetwork()
from networkd3, with the source countries on the left and the target countries on the right and the flows represented. How do I define the nodes and links data frames properly?
I have these lines:
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
I got his error message: Error in Links[, Source] : incorrect number of dimensions
推荐答案
我相信您在谈论的是networkD3
中的sankeyNetwork()
函数,而不是plotly
包.假设是这种情况,这是一个最小的可重现示例,演示您的特定用例.
I believe you're talking about the sankeyNetwork()
function from networkD3
, not the plotly
package. Assuming that's the case, here is a minimal reproducible example demonstrating your particular use case.
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")
这篇关于如何为sankeyNetwork()定义节点和链接数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!