Sankey network manual colour change
Asked Answered
R

1

5

I am trying to build sankey plot using networkD3 library. I have following code and data:

# Plotting the Sankey network diagram
nodes = data.frame("name" = 
                     c("Mamalian", # Node 0
                       "Avian", # Node 1
                       "Critical", # Node 2
                       "Critical-maintained", # Node 3
                       "Endangerd", #Node 4
                       "Endangered-maintained", #Node 5
                       "Not at risk")) # Node 6

links = as.data.frame(matrix(c(
  0, 2, 16, # Note the values in the final column refer to the % of breeds in each risk category
  0, 3, 2.2, 
  0, 4, 17.6, 
  0, 5, 7.0,
  0, 6, 57.2,
  1, 2, 23.9, 
  1, 3, 1.3, 
  1, 4, 24.7, 
  1, 5, 13.1,
  1, 6, 37.0),
  byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankeyNetwork(Links = links, Nodes = nodes,
              Source = "source", Target = "target",
              Value = "value", NodeID = "name",
              fontSize= 12, nodeWidth = 30, iterations = 0)

I want to manually change the colours associated with each node, as they ddo not currently correspond with the endangerment categories I have listed. How can I do this?

Here is the result: enter image description here

Rosanne answered 26/1, 2018 at 9:54 Comment(1)
See this post, you can define a "group" for nodes dataframe, then each node will be assigned some colour per grouping. But can't see how we can set custom colours, maybe using colourScale.Disconformity
E
6

Use the colourScale parameter to set a custom JS/D3 color scale. (I replaced spaces in your names with - because d3.scaleOrdinal() doesn't like them). Using your data/objects from your example....

nodes$group <- gsub(" ", "-", nodes$name)

color_scale <- 
  "d3.scaleOrdinal()
     .domain(['Mamalian', 'Avian', 'Critical', 'Critical-maintained', 
              'Endangerd', 'Endangered-maintained', 'Not-at-risk'])
     .range(['#000', '#F00', '#0F0', '#00F', '#FF0', '#F0F', '#0FF']);
  "
sankeyNetwork(Links = links, Nodes = nodes,
              Source = "source", Target = "target",
              Value = "value", NodeID = "name", 
              fontSize= 12, nodeWidth = 30, iterations = 0,
              NodeGroup = "group", colourScale = color_scale)
Ewart answered 26/1, 2018 at 14:35 Comment(1)
CJ Yetman, thank you so much. All of your answers regarding Sankey- diagram is helping me a lot.Kirtley

© 2022 - 2024 — McMap. All rights reserved.