Modify networkD3 sankey plot with user-defined colors

别等时光非礼了梦想. 提交于 2019-12-03 07:40:20

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!