I am working on making a sankey diagram in R, but having trouble with the LinkGroup
code. I attach parts of my code which should explain the problem and the head of the data. I have a current plot without the legend of products, and I also attach what I eventually want R to do automatically with the LinkGroup
function (right now I constructed the legend manually for illustration).
I currently have a sankey diagram with source and target (countries), with products ('major_prod') transferred between the source and target. I want to show the legend containing the different products transferred (beef, palm oil, wheat etc.)
Here is a reproducible example. The problem remains that the sankey has colour, but the legend of the product (Meat, palm oil, rice nuts etc.) does not show.
library(htmltools)
library(htmlwidgets)
library(magrittr)
library(networkD3)
library(tidyr)
Sankey <- data.frame("origin" = c('country A', 'country A', 'country A', 'country A', 'country B', 'country B', 'country C', 'country C'),
"destination" = c('country B', 'country B', 'country C', 'country D', 'country D', 'country D', 'country E', 'country E'),
'product' = c('Meat', 'Palm oil', 'Meat', 'Meat', 'Wheat', 'Other', 'Rice', 'Nuts'),
'number' = c(10, 10, 20, 30, 40, 35, 50,10))
nodes <- as.data.frame(union(unique(Sankey$origin), unique(Sankey$destination))) %>%
rename(Countries = 1)
Sankey$ID_major_Origin_EU <- match(Sankey$origin, nodes$Countries)-1
Sankey$ID_major_Destination_EU <- match(Sankey$destination, nodes$Countries)-1
Sankey$ID_major_Origin_EU <- match(Sankey$origin, nodes$Countries)-1
Sankey$ID_major_Destination_EU <- match(Sankey$destination, nodes$Countries)-1
head(Sankey)
nodes %<>% tidyr::separate(Countries, "Countries", sep = "_")
sankeyNetwork(Links = Sankey,
Nodes = nodes,
Source = "ID_major_Origin_EU", Target = "ID_major_Destination_EU",
Value = "number", NodeID = "Countries",
units = "t dm", fontSize = 20, nodeWidth = 30,
height = 600,
#sinksRight = T,
LinkGroup = c("product")) %>%
htmlwidgets::prependContent(htmltools::tags$h1("2013 - embodied HANPP"))
I want to show a legend containing the 'product' on the side of the sankey diagram but I cannot find a way. Any hints or solutions?