I am working on a sankey diagram in R following some tutorials using networkD3 package.
I do not understand what is not working since when I run my codes, they work but in the Viewer it doesn’t appear the diagram. I attach my codes and example of my data.
Thanks a lot,
CODES:
# import packages
library(readxl)
library(networkD3)
nodes <- read_excel("prova_sankey.xlsx", sheet = "nodes", col_types = c("text", "text"))
links <- read_excel("prova_sankey.xlsx", sheet = "links", col_types = c("numeric", "text", "numeric", "numeric"))
sankeyNetwork(Links=links, Nodes= nodes, Source= "source", Target="target", Value="value", NodeID="name")
DATA:
LINKS
source | target | value |
---|---|---|
10 | 35 | 1152 |
10 | 40 | 100 |
12 | 40 | 156 |
NODES
id | name |
---|---|
35 | Died |
40 | Survived |
10 | Good |
12 | Bad |
2
You probably need to use the zero-indexed row number of each node in the nodes data frame as the index pointed to in the links data frame, e.g.
links <-
data.frame(
source = c(10, 10, 12),
id = c("A", "B", "C"),
target = c(35, 40, 40),
value = c(1152, 100, 156)
)
nodes <-
data.frame(
id = c("35", "40", "10", "12"),
name = c("Died", "Survived", "Good", "Bad")
)
tibble::as_tibble(links)
#> # A tibble: 3 × 4
#> source id target value
#> <dbl> <chr> <dbl> <dbl>
#> 1 10 A 35 1152
#> 2 10 B 40 100
#> 3 12 C 40 156
tibble::as_tibble(nodes)
#> # A tibble: 4 × 2
#> id name
#> <chr> <chr>
#> 1 35 Died
#> 2 40 Survived
#> 3 10 Good
#> 4 12 Bad
# doesn't work
# networkD3::sankeyNetwork(Links=links, Nodes= nodes, Source= "source", Target="target", Value="value", NodeID="name")
links$source_id <- match(links$source, nodes$id) - 1
links$target_id <- match(links$target, nodes$id) - 1
networkD3::sankeyNetwork(Links=links, Nodes= nodes, Source= "source_id", Target="target_id", Value="value", NodeID="id")
Created on 2024-09-04 with reprex v2.1.1