问题
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)
I got his error message: Error in Links[, Source] : incorrect number of dimensions
回答1:
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")
来源:https://stackoverflow.com/questions/51597028/how-to-define-nodes-and-links-data-frame-for-sankeynetwork