如何创建网络图表?

How to create a network chart?

我正在尝试使用 networkD3::forceNetwork 创建雇主和雇主雇佣雇员的大学图表。

现在,我有这样的东西:

forceNetwork(Links= Links, Nodes= netDf , 
             Source = 'collegeName', Target = 'organizationName', Value='count',
             NodeID = 'collegeName', Group = 'organizationName')

但是输出看起来不像预期的那样。我想要的是:

  1. 每所大学一个泡泡
    1. 每个雇主一个泡泡
    2. 学院连接到雇主,雇主数量(count)映射到连接线的宽度。

大学之间从来没有联系,雇主也是如此。

这是我正在使用的数据集netDf:

 structure(list(collegeName = c("college1", "college1", "college2", 
"college3", "college3", "college3", "college4", "college5", "college5", 
"college6", "college6", "college6", "college7", "college7", "college7", 
"college8", "college9", "college10", "college10", "college11"
), organizationName = c("employer2", "employer3", "employer2", 
"employer1", "employer2", "employer3", "employer2", "employer2", 
"employer3", "employer1", "employer2", "employer3", "employer1", 
"employer2", "employer3", "employer2", "employer2", "employer2", 
"employer3", "employer2"), count = c(858, 176, 461, 201, 2266, 
495, 430, 1992, 290, 127, 1754, 549, 136, 2839, 686, 638, 275, 
1388, 387, 188), group = c(2, 3, 2, 1, 2, 3, 2, 2, 3, 1, 2, 3, 
1, 2, 3, 2, 2, 2, 3, 2)), .Names = c("collegeName", "organizationName", 
"count", "group"), row.names = c(NA, -20L), class = "data.frame")

这是 Links 数据集:

structure(list(collegeName = c(0, 0, 1, 2, 2, 2, 3, 4, 4, 5, 
5, 5, 6, 6, 6, 7, 8, 9, 9, 10), organizationName = c(1, 2, 1, 
0, 1, 2, 1, 1, 2, 0, 1, 2, 0, 1, 2, 1, 1, 1, 2, 1), count = c(858, 
176, 461, 201, 2266, 495, 430, 1992, 290, 127, 1754, 549, 136, 
2839, 686, 638, 275, 1388, 387, 188), group = c(2, 3, 2, 1, 2, 
3, 2, 2, 3, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 2)), .Names = c("collegeName", 
"organizationName", "count", "group"), row.names = c(NA, -20L
), class = "data.frame")

此外,是否可以将第 4 个变量映射到气泡大小?例如,我想将 count 映射到与员工相关的气泡的大小,我该怎么做?

我认为您的 LinksNodes 数据框不符合 ?forceNetwork 中指定的要求。相反,你可以这样做:

library(networkD3)
set.seed(1)

nodes <- data.frame(Label = unique(c(netDf[,1], netDf[,2])))
nodes$Group <- as.factor(substr(nodes$Label, 1, 3))
nodes <- merge(
  nodes, 
  aggregate(count~organizationName, netDf, sum), 
  by.x="Label", by.y="organizationName", 
  all.x=TRUE
)
nodes$count[is.na(nodes$count)] <- 1

links <- transform(netDf, 
  Source = match(netDf$collegeName, nodes$Label)-1, 
  Target = match(netDf$organizationName, nodes$Label)-1
)

forceNetwork(
  Links = transform(links, count = count/min(count)), 
  Nodes = nodes, 
  Source = 'Source', 
  Target = 'Target', 
  Value='count',
  NodeID = 'Label', 
  Group = "Group", 
  Nodesize = "count",
  legend = TRUE, 
  opacity = 1,
  radiusCalculation = JS("Math.log(d.nodesize)+6")
)