我们如何在包networkD3的forceNetwork功能中找到组?

时间:2019-05-02 11:33:15

标签: r htmlwidgets networkd3

我正在尝试使用包和功能forceNetwork,即

中创建D3网络。
forceNetwork(Links = MisLinks, Nodes = MisNodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "name",
             Group = "group", opacity = 0.8)

我想知道,他们是在什么基础上分组的。

R中的示例数据提供了两个表来创建网络,

1)   MisLink: which gives information about the links
header:   |source |target |value
     1    |  1    |  0    | 1
     2    |  2    |  0    | 8
     3    |  3    |  0    |10
     4    |  3    |  2    | 6
     5    |  4    |  0    | 1

2) MisNode: which consists of information regarding nodes.
header:  |              name| group| size
       1 |          Myriel  |   1  | 15
       2 |        Napoleon  |   1  | 20
       3 | Mlle.Baptistine  |   1  | 23
       4 |    Mme.Magloire  |   1  | 30
       5 |    CountessdeLo  |   1  | 11

“我的节点”数据没有任何组列。如何创建GROUP列?

我有两个表,如下所示:

Link Table:

Source |    Target     |  EdgeWt
5-HT1A |    depression |    4
5-HT2A |    depression |    5
5-HT2C |    Anxiety    |    3
5-HT2C |    depression |    4

Node Table:

Id     | NodeType
5-HT1A | GeneSymbol
5-HT2A | GeneSymbol
5-HT2C | GeneSymbol
ACNE   | Disease
ACTA   | GeneSymbol
ACTH   | GeneSymbol

我可以将Source(源)和Target(目标)更改为数字,但是最后我希望基于NodeType的节点颜色。

1 个答案:

答案 0 :(得分:0)

如果未对节点进行分组,则只需在节点数据中添加一个组列,其中每个节点的值都相同,例如...

myLinks$group <- 1

如果将数据分组,则将其添加到“节点”数据框中并在Group参数中引用该列名称。


鉴于您添加的数据,这是可以实现的方式(Group = "NodeType")...

links <-
  data.frame(
    stringsAsFactors = FALSE,
    Source = c("5-HT1A", "5-HT2A", "5-HT2C", "5-HT2C"),
    Target = c("depression", "depression", "Anxiety", "depression"),
    EdgeWt = c(4, 5, 3, 4)
  )

nodes <- data.frame(
  stringsAsFactors = FALSE,
  Id = c("5-HT1A", "5-HT2A", "5-HT2C", "ACNE", "ACTA", "ACTH"),
  NodeType = c(
    "GeneSymbol",
    "GeneSymbol",
    "GeneSymbol",
    "Disease",
    "GeneSymbol",
    "GeneSymbol"
  )
)

nodes <- rbind(nodes, c("depression", "Disease"), c("Anxiety", "Disease"))

links$Source <- match(links$Source, nodes$Id) - 1
links$Target <- match(links$Target, nodes$Id) - 1

library(networkD3)

forceNetwork(Links = links, Nodes = nodes,
             Source = "Source", Target = "Target",
             Value = "EdgeWt", NodeID = "Id",
             Group = "NodeType", opacityNoHover = 1, 
             opacity = 1, fontSize = 10)

enter image description here