I am making a Sankey graph and want to colour the nodes and links individually (ideally having the links the same colour as the source node).
I've researched on various forums and put together the following code for the colours. However, all I get is the 1st part of the Sankey graph, and it is all in black.
Data:
library(networkD3)
## create a dataframe with 10 nodes
nodes = data.frame("name" = c("0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12"))
#Create column column to nodes dataframe for colours
nodeColor <- c("#50A14D", "#52CC4E", "#9D73E6", "#F54F4F", "#F7A85E", "#9D73E6", "#F54F4F", "#F7A85E",
"#ADFBFF", "#ADDAFF", "#ADC3FF", "#BBADFF", "#E9ADFF")
#Add colour column to nodes dataframe
nodes["nodesColor"] <-nodeColor
#Set Colours for each group
mycolor <- 'd3.scaleOrdinal() .domain(["0", "1", "2", "3", "4", "5", "6", "7"]).range
(["#50A14D", "#52CC4E" ,"#9D73E6", "#F54F4F", "#F7A85E", "#9D73E6",
"#F54F4F", "#F7A85E"])'
## create links with values (1st number = Source, 2nd number = Target, 3rd number = Value)
links = as.data.frame(matrix(c(0, 2, 10,
0, 3, 212,
0, 4, 84,
1, 2, 7,
1, 3, 13,
1, 4, 70,
2, 5, 102,
2, 6, 8,
2, 7, 36,
3, 5, 11,
3, 6, 102,
3, 7, 29,
4, 5, 8,
4, 6, 8,
4, 7, 176,
5, 8, 51,
5, 9, 32,
5, 10, 24,
5, 11, 8,
5, 12, 12,
6, 8, 82,
6, 9, 42,
6, 10, 41,
6, 11, 11,
6, 12, 23,
7, 8, 25,
7, 9, 27,
7, 10, 22,
7, 11, 3,
7, 12, 8
), byrow = TRUE, ncol = 3))
#Create Grouping Column for Colours
group <- c(0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,5,5,6,6,6,6,6,7,7,7,7,7)
#Add Group Column to Links dataframe
links["group"] <- group
## set column names for links
names(links) = c("source", "target", "value", "group")
Graph:
sankeyNetwork(
Links = links,
Nodes = nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "name",
LinkGroup = "group",
colourScale = mycolor,
fontFamily = "Arial",
nodeWidth = 15,
fontSize = 12,
width = 400,
height = 300)
How can I make the nodes and links have different colors?
The links$group
column/vector needs to be character, not numeric. So just convert it like this and then run your same sankeyNetwork()
command again...
links$group <- as.character(links$group)