如何在d3教程中映射节点对象到节点id



我正在学习这个教程-

http://flowingdata.com/2012/08/02/how-to-make-an-interactive-network-visualization/

有一部分我不明白。

"最后,我们将节点id映射到节点对象,然后用节点对象本身替换链接中的源和目标,而不是原始数据中的id。这允许D3的强制布局正确工作,并使添加/删除节点成为可能,而不必担心我们的节点数组和链接数组乱序。"

setupData = (data) ->
  # initialize circle radius scale
  countExtent = d3.extent(data.nodes, (d) -> d.playcount)
  circleRadius = d3.scale.sqrt().range([3, 12]).domain(countExtent)
  data.nodes.forEach (n) ->
    # set initial x/y to values within the width/height
    # of the visualization
    n.x = randomnumber=Math.floor(Math.random()*width)
    n.y = randomnumber=Math.floor(Math.random()*height)
    # add radius to the node so we can use it later
    n.radius = circleRadius(n.playcount)
  # id's -> node objects
  nodesMap  = mapNodes(data.nodes)
  # switch links to point to node objects instead of id's
  data.links.forEach (l) ->
    l.source = nodesMap.get(l.source)
    l.target = nodesMap.get(l.target)
    # linkedByIndex is used for link sorting
    linkedByIndex["#{l.source.id},#{l.target.id}"] = 1
  data

这是在关于函数setupData()的部分之后说的。我不明白将节点id映射到节点对象意味着什么,因为节点对象似乎是在之后由update()方法创建的。

这些节点对象是什么?mapNodes()

在创建力有向图时,必须提供每个节点的数据以及节点之间的连接方式。它们如何连接的信息由force.links([])方法设置,该方法直接在力图上调用。链接数组中的每个数据点都有一个源和一个目标,它们被定义为索引(数据数组中的位置)或数组本身中的实际对象。

var banana = {type: "fruit", color: "yellow"};
var apple = {type: "fruit", color: "red"};
..etc
var data = [apple, banana, sausage, peach, bagel, kimchee.. etc etc ]
var links = [{source: 1,target: 2}, 
             {source: 2, target: 10}, ....etc. ] //as index

 var links = [{source:banana,target:apple},
              {source:apple, target:orange}, 
              ....etc. ] //as object

在初始数据中,每首歌都有一个id,源/目标只是被定义为指向这些id。在此步骤中,他将匹配id的实际对象替换为初始id字符串。

最新更新