我正在尝试使用 R 中的 networkD3 创建桑基图。
我尝试创建一个最小的示例,但在代码中已经失败了。我尝试过,但甚至没有显示三个正确的列:
#Load required library
library(networkD3)
# Create a data frame with the nodes and links
nodes <- data.frame(name = c("Asia", "Europe", "NA", "Asia", "Europe", "NA", "Asia", "Europe", "NA"))
links <- data.frame(source = c(0, 0, 1, 1, 2, 2, 3, 3, 4),
target = c(3, 4, 3, 4, 3, 4, 5, 5, 5),
value = c(2, 3, 1, 2, 4, 3, 4, 4, 1))
# Create the Sankey diagram
sankey <- sankeyNetwork(Links = links, Nodes = nodes, Source = "source", Target = "target", Value = "value", units = "TWh", fontSize = 12, nodeWidth = 30)
# Display the Sankey diagram
print(sankey)
将数据转换为正确的格式很麻烦。我使用文档中的示例作为基准:
library(networkD3)
networkD3
URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)
sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
Target = 'target', Value = 'value', NodeID = 'name',
units = 'TWh', fontSize = 12, nodeWidth = 30)
head(energy)
> head(energy)
#$nodes
# name
#1 Agricultural 'waste'
#2 Bio-conversion
#3 Liquid
#4 Losses
#5 Solid
#...
#$links
# source target value energy_type
#1 0 1 124.729 Agricultural
#2 1 2 0.597 Bio-conversion
#3 1 3 26.862 Bio-conversion
#4 1 4 280.322 Bio-conversion
#5 1 5 81.144 Bio-conversion
#...
str(energy)
#List of 2
# $ nodes:'data.frame': 48 obs. of 1 variable:
# ..$ name: chr [1:48] "Agricultural 'waste'" "Bio-conversion" "Liquid" "Losses" ...
# $ links:'data.frame': 68 obs. of 4 variables:
# ..$ source : int [1:68] 0 1 1 1 1 6 7 8 10 9 ...
# ..$ target : int [1:68] 1 2 3 4 5 2 4 9 9 4 ...
# ..$ value : num [1:68] 124.729 0.597 26.862 280.322 81.144 ...
# ..$ energy_type: chr [1:68] "Agricultural" "Bio-conversion" "Bio-conversion" "Bio-conversion" ...