networkD3中的forcenetwork不产生图并且没有错误

时间:2019-03-20 17:32:19

标签: r networkd3

我正在尝试使用R中的networkD3生成一个简单的forcenetwork图,但是使用下面的代码我没有得到任何输出或错误。我已经确认我的节点ID为0索引,数值和名称/组字段均为字符。任何帮助表示赞赏。

# Load Packages

library(dplyr)
library(networkD3)

zz <- "name id  group   source  target  value
A   0   A   0   1   2199
B   1   A   1   0   784
C   2   B   2   4   394
D   3   B   3   2   382
E   4   B   4   8   340
F   5   B   5   9   286
G   6   B   6   5   279
H   7   A   0   7   279
I   8   B   7   0   240
J   9   B   8   0   196
K   10  A   9   0   174"

df<- read.table(text=zz, header = TRUE)

nodes <- df %>%
  select(name,id,group) %>%
  mutate(name = as.character(name),id = as.numeric(id), group=as.character(group))

links <- df %>%
  select(source,target,value) %>%
  mutate(source = as.numeric(source),target=as.numeric(target),value=as.numeric(value))


# simple with default colours
forceNetwork(Links = links, Nodes = nodes, 
             Source = "source",
             Target = "target",
             NodeID ="name",
             Group = "group",
             Value = "value",
             Nodesize = 1,
             width = "1000px", 
             height = "600px",
             opacity = 0.9,
             zoom = TRUE)

sapply(nodes,class)
sapply(links, class)

1 个答案:

答案 0 :(得分:2)

尝试一下:

forceNetwork(Links = links, Nodes = nodes, 
             Source = "source",
             Target = "target",
             NodeID ="name",
             Group = "group",
             Value = "value",
           #  Nodesize = 1,
             width = "1000px", 
             height = "600px",
             opacity = 0.9,
             zoom = TRUE)

?forceNetwork中可以看到:

  

Nodesize字符串,它指定Nodes数据中的一列   带有一些值的框架以改变节点半径。也可以看看   radiusCalculation。

所以您说的是希望第1列是节点的大小,但是它需要一个字符串来引用该列,即使接受位置,节点data.frame中第1列也不是大小而是名称。

因此,如果要确定Nodesize,请在节点中创建一个新列,然后分配所需的值。然后,将该列的名称传递到Nodesize

library(dplyr)
library(networkD3)

zz <- "name id  group   source  target  value
A   0   A   0   1   2199
B   1   A   1   0   784
C   2   B   2   4   394
D   3   B   3   2   382
E   4   B   4   8   340
F   5   B   5   9   286
G   6   B   6   5   279
H   7   A   0   7   279
I   8   B   7   0   240
J   9   B   8   0   196
K   10  A   9   0   174"

df<- read.table(text=zz, header = TRUE)

nodes <- df %>%
  select(name,id,group) %>%
  mutate(name = as.character(name),id = as.numeric(id), group=as.character(group))

links <- df %>%
  select(source,target,value) %>%
  mutate(source = as.numeric(source),target=as.numeric(target),value=as.numeric(value))

nodes<-nodes %>% mutate(size=100)


forceNetwork(Links = links, Nodes = nodes, 
             Source = "source",
             Target = "target",
             NodeID ="name",
             Group = "group",
             Value = "value",
            Nodesize = "size",
             width = "1000px", 
             height = "600px",
             opacity = 0.9,
             zoom = TRUE)