How to color groups in networkD3's sankeyNetwork?

[亡魂溺海] 提交于 2019-12-19 03:56:39

问题


My nodes consists of names and groups yet I can't seem to implement distinct colors for groups in my sankey diagram. The colors are either all blue with defaults or all black using the code below.

Here's the code I use:

sankeyNetwork(        
Links = data$links,
Nodes = data$nodes,
Source= "source",
Target = "target",
Value = "weight",
NodeID = "names",
fontSize = 15,
NodeGroup = "group" 
))

Here's the output I'm getting:


回答1:


The NodeGroup vector in the Nodes data frame needs to be non-numeric. That's not obvious from the documentation. Because you didn't provide the data you're working with, we can't be sure if that is the problem you were having, but in the example that @john-friel made, that is the problem. Here's a working example with the only change being that the group vector is coerced to a character vector...

library(networkD3)
source <- c(0,1,2,3,4,5)
target <- c(2,2,2,3,1,0)
value <- c(33,44,55,66,77,88)

sankeydata <- data.frame(source,target, value)

names <- c('a', 'b', 'c', 'd', 'e', 'f')
id <- c(0,1,2,3,4,5)
group <- as.character(c(1,1,1,2,2,2)) # this is the only line changed

sankeyNodes <- data.frame(names,id, group)


sankeyNetwork(Links = sankeydata, Nodes = sankeyNodes, Source = "source",
         Target = "target", Value = "value", NodeID = "names", 
         NodeGroup = "group", fontSize = 12, nodeWidth = 30)




回答2:


library(networkD3)
source <- c(0,1,2,3,4,5)
target <- c(2,2,2,3,1,0)
value <- c(33,44,55,66,77,88)

sankeydata <- data.frame(source,target, value)

names <- c('a', 'b', 'c', 'd', 'e', 'f')
id <- c(0,1,2,3,4,5)
group <- c(1,1,1,2,2,2)

sankeyNodes <- data.frame(names,id, group)


sankeyNetwork(Links = sankeydata, Nodes = sankeyNodes, Source = "source",
         Target = "target", Value = "value", NodeID = "names", NodeGroup = "group", fontSize = 12, nodeWidth = 30)

I would expect two colors ( since there are two groups), but no colors return. I have the same issue as OP.

The help text suggests NodeGroup is responsible for the color.

If you run a similar code for another graph in library(networkD3):

#same data
forceNetwork(Links = sankeydata, Nodes = sankeyNodes , Source = "source",
         Target = "target", Value = "value", NodeID = "names",
         Group = "group", opacity = 0.8, zoom = TRUE)

Plots two different colors for in the network graph.



来源:https://stackoverflow.com/questions/35823962/how-to-color-groups-in-networkd3s-sankeynetwork

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