networkD3 customize node colors based on the existing nodes

I am making some sankey diagrams using R's networkD3 package. I have an application that produces different sankey diagrams based on inputs the user sets. I know there is a maximum number of nodes that might display in any one diagram, but sometimes, depending on the inputs, less than the maximum number of nodes will display. I'd like the colors for the nodes to be consistent from one diagram to the next. (i.e. Node 0 should always be red, Node 3 should always be blue, etc...)

If I use the defaults in the package for coloring then this doesn't occur and I am trying to figure out how to fix a custom color to each unique node.

1 Like

Actually, I solved this issue myself. You need to first specify what nodes you want to color in the node data frame. I use the "group" column to identify what nodes should have the same color. For example, for a network with three nodes, my nodes data frame will look like this:

nodes = data.frame(id = c(0,1,2), name = c("Node 1", "Node 2", "Node 3"), group = c("1","2","3"))

I'm giving each node a unique group ID so that means each node will be a different color. In the sankeyNetwork function you set NodeGroup = "group" so that it knows what nodes should be colored the same.

You'll also need to change the colourScale argument with a domain and range. The domain should correspond to the group ID in the node data frame.

JS('d3.scaleOrdinal().domain(["1", "2", "3"]).range(["#000000", "#111111", "#222222"])')

This will fix the first node's color to be black (#000000), the second node's color to be #111111 and the third node's color to be #222222. If you have more nodes/colors you can just add them to domain/range.

2 Likes