I am looking for help colouring the links between nodes in a sankey plot. I am using the networkD3 package in R to create the plot. Here is a very simple example of what I'd like to achieve:
library(networkD3)
nodes <- c("a", "b", "c")
source <- c(0, 0)
target <- c(1, 2)
value <- c(5, 5)
cbind(source, target, value) -> links
as.data.frame(links) -> links
as.data.frame(nodes) -> nodes
sankeyNetwork(Links=links, Nodes=nodes, Source="source",
Target="target", Value="value")
The above code creates a simple sankey diagram with links to 2 nodes, "b" and "c", from "a". What I'd like to do is simply colour each link, not node, a different colour. For example, a->b would be green, and a->c would be yellow. I have tried to follow other examples which manipulate the colour scale using d3.scaleOrdinal() but I have not had any luck. The plot either doesn't render, or remains grey throughout.
library(networkD3)
nodes<-c("a","b","c")
source<-c(0,0)
target<-c(1,2)
value<-c(5,5)
cbind(source,target,value)->links
as.data.frame(links)->links
as.data.frame(nodes)->nodes
links$group <- "blue"
my_color <- 'd3.scaleOrdinal() .domain(["blue"]) .range(["blue"])'
sankeyNetwork(Links = links,Nodes = nodes,Source = "source",Target =
"target",Value = "value", colourScale=my_color, LinkGroup="group")
You need to create a new column in your links naming the links you want to paint and the map using d3.scaleOrdinal each name with a color. Finally, pass those to sankeyNetwork. The example above will paint all links as blue
library(networkD3)
nodes<-c("a","b","c")
source<-c(0,0)
target<-c(1,2)
value<-c(5,5)
cbind(source,target,value)->links
as.data.frame(links)->links
as.data.frame(nodes)->nodes
links$group[1] <- "blue"
links$group[2] <- "green"
my_color <- 'd3.scaleOrdinal() .domain(["blue", "green"]) .range(["blue", "green"])'
sankeyNetwork(Links = links,Nodes = nodes,Source = "source",Target =
"target",Value = "value", colourScale=my_color, LinkGroup="group")
THis one will do it blue and green
See more here: https://www.r-graph-gallery.com/322-custom-colours-in-sankey-diagram/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With