如何为sankeyNetwork()定义节点和链接数据框 [英] how to define nodes and links data frame for sankeyNetwork()

查看:372
本文介绍了如何为sankeyNetwork()定义节点和链接数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从源国家/地区到目标国家/地区出口的文件,贸易价值在Before_value维度中. 我的数据在data.table中,其中尺寸sourcetarget为字符(国家代码列表)和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.

我想使用,左侧是来源国,右侧是目标国,代表流量.如何定义节点并正确链接数据帧? 我有以下几行:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆