0

I am trying to make a Sankey diagram in R using the networkD3 package with user-defined colors. I would like to make the flows colored as gradients between the nodes, as in this example: this example

Here is a reproducible example:

library(tidyverse)
library(networkD3)

source <- c("s1","s3","s2")
target <- c("t3","t1","t2","t4")
sankey_data <- expand.grid(source, target) %>%
  rename("source" = "Var1", "target" = "Var2")
sankey_data <- sankey_data %>%
  mutate(value=c(234,31289,48,NA,23787,9,NA,474,8484,923,94,8478)) %>%
  na.omit()
nodes <- data.frame(name=c(as.character(sankey_data$source), as.character(sankey_data$target))
                    %>% unique())
sankey_data$IDsource=match(sankey_data$source, nodes$name)-1
sankey_data$IDtarget=match(sankey_data$target, nodes$name)-1
# Custom colors
ColourScal='d3.scaleOrdinal().range(["#00441B","#E0C2E7","#33A02C","#313695","#FDAE61","#ABD9E9","#F8D26F"])'
# Make the network
sankeyNetwork(Links = sankey_data,
              Nodes = nodes,
              Source = "IDsource",
              Target = "IDtarget",
              Value = "value",
              NodeID = "name",
              sinksRight=TRUE,
              colourScale=ColourScal,
              nodeWidth=40,
              fontSize=13,
              nodePadding=20)

Resulting Diagram

I saw another similar post where someone was able to write some custom JavaScript with the htmlwidgets package, and I played around with this but I don't know any JavaScript so I haven't been able to figure it out. Can anyone help?

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
  • It looks like `networkD3` hasn't been updated for a few years now. Maybe this functionality is not available in the d3 sankey version it's using. There is an [observable HQ template](https://observablehq.com/@d3/sankey/2?intent=fork) that supports the gradient functionality you are looking for. – Till Jul 25 '23 at 21:29

0 Answers0