如何创建网络图表?

时间:2016-09-18 22:34:19

标签: r networkd3

我正在尝试使用networkD3::forceNetwork创建一份雇主雇用员工的雇主和学院的图表。

现在,我有这样的事情:

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

但输出并不像预期的那样。我想拥有的是:

  1. 每个大学都有一个泡沫
    1. 每个雇主的一个泡沫
    2. 与雇主相关的学院,雇主数量(count)映射到连接线的宽度。
  2. 大学永远不会相互联系,雇主也是如此。

    这是我使用的数据集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映射到与员工有关的泡沫大小,我该怎么做?

1 个答案:

答案 0 :(得分:3)

我认为您的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")
)

enter image description here