Skip to content Skip to sidebar Skip to footer

Modify Networkd3 Sankey Plot With User-defined Colors

I have a sankey plot created in networkD3 package. I would like to modify the colors and transparency of both nodes and links. My data networkD3_data is appended at the end. Quest

Solution 1:

The color pallete is determined by the colourScale argument. It should be a string containing valid D3 code to define the palette. In the current version of networkD3, which uses D3v4+, the syntax d3.scaleOrdinal().range(["#7d3945", "#e0677b", "#244457"]) is valid, though it could be shortened to d3.scaleOrdinal(["#7d3945", "#e0677b", "#244457"]). There are other possibilites as well, see here. The number of colors in the palette you choose/define must be equal to or greater than the total number of unique groups defined in your data, otherwise it will loop back to the beginning of your color palette to assign colors to further groups. The first group defined in your data will be assigned the first color in your color palette, and so forth.

The NodeGroup and LinkGroup parameters define the name of the column in your Nodes and Links data.frames, respectively, that define the group value for each node/link. Both nodes and links will be colored according to their group value and its assigned color based on the color palette being used.

Setting the iteration argument to 0 will effectively prevent the placement algorithm from running, so your nodes will be ordered as they were in the original data. As you've pointed out, this essentially defeats the primary purpose of sankeyNetwork.

Using the data you posted...

library(networkD3)

colors <- paste(networkD3_data$nodes$colors, collapse = '", "')
colorJS <- paste('d3.scaleOrdinal(["', colors, '"])')

sankeyNetwork(Links = networkD3_data$links, Nodes = networkD3_data$nodes, 
              Source = 'source', Target = 'target', Value = 'value', 
              NodeID = 'name', NodeGroup = "group", LinkGroup = "group",
              colourScale = colorJS,
              iterations = 0)

Transparency/opacity can be achieved by setting RGBA colors in the D3 color palette, but you'll need to use the decimal RGB notation (as far as I can tell). You'll want to convert something like #ff0043 into something like d3.rgb(255,0,67,0.5), where the last number is a number between 0 and 1 that defines the level of opacity. For example...

colors <- paste(sapply(networkD3_data$nodes$colors, function(x) { paste0("d3.rgb(", paste(c(col2rgb(x), 0.5), collapse = "," ), ")") }), collapse = ", ")
colorJS <- paste0('d3.scaleOrdinal([', colors, '])')
sankeyNetwork(Links = networkD3_data$links, Nodes = networkD3_data$nodes,
              Source = 'source', Target = 'target', Value = 'value',
              NodeID = 'name', NodeGroup = "group", LinkGroup = "group",
              colourScale = colorJS,
              iterations = 0)

Post a Comment for "Modify Networkd3 Sankey Plot With User-defined Colors"