【问题标题】:How to map node objects to node Ids in d3 tutorial?如何在 d3 教程中将节点对象映射到节点 ID?
【发布时间】:2013-04-07 05:29:16
【问题描述】:

我正在学习本教程 -

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() 会怎样

【问题讨论】:

    标签: javascript coffeescript d3.js


    【解决方案1】:

    创建力有向图时,您必须提供每个节点的数据以及节点的连接方式。它们如何连接的信息由在力图上直接调用的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
    

    initial data 中,每首歌曲都有一个 id,而源/目标只是定义为指向这些 id。通过这一步,他将与 id 匹配的实际对象替换为初始 id 字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多