R Shiny的ColourScale ForceNetwork(NetworkD3)

时间:2017-09-19 11:46:34

标签: r shiny htmlwidgets networkd3

在力网中,我发现了group和colourscale来为网络中的节点着色。我想有2个不同的组(根据2个不同变量之间的用户输入,颜色应用于节点)。有可能吗?如果是,怎么样?

Forcenetwork - https://www.rdocumentation.org/packages/networkD3/versions/0.4/topics/forceNetwork

任何形式的帮助都会有用。 谢谢!

1 个答案:

答案 0 :(得分:1)

colourScale参数确定调色板,而group参数确定节点数据框中包含用于区分每个节点组的值的向量名称。 networkD3会自动从数据调色板中为数据中的每个不同组选择一种独特的颜色,并将该颜色应用于该组中的每个节点。

library(networkD3)

links <- read.table(header = T, text = "
source  target  value
0       1       1
1       2       1
2       0       1
0       3       1
3       4       1
4       5       1
5       3       1
")

nodes <- read.table(header = T, text = "
name    group
zero    1
one     1
two     1
three   2
four    2
five    2
")

forceNetwork(Links = links, Nodes = nodes, 
             Source = "source", Target = "target", Value = "value", 
             NodeID = "name", Group = "group", 
             colourScale = JS("d3.scaleOrdinal(d3.schemeCategory10);"))

如果您的数据中有两个单独的变量共同决定每个节点的组,您应该将它们合并到数据中,然后再将它们传递给forceNetwork() ...

nodes <- read.table(header = T, text = "
name    group1  group2
zero    A       D
one     B       E
two     C       F
three   A       E
four    B       F
five    C       D
")

nodes$group <- paste(nodes$group1, nodes$group2, sep = "_")

forceNetwork(Links = links, Nodes = nodes, 
             Source = "source", Target = "target", Value = "value", 
             NodeID = "name", Group = "group", 
             colourScale = JS("d3.scaleOrdinal(d3.schemeCategory10);"))