Is there a way to create a color gradient for the flows in a Sankey diagram using networkD3 in R?

78 Views Asked by At

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?

0

There are 0 best solutions below