2013-05-11 78 views
1

(這是一個後續問題的一問here,這個問題並沒有在這個問題徹底解決了,這是怎樣的一個延續,所以我發佈了一個新問題)使用json D3嵌套選擇:如何將.force()應用於嵌套元素?

我有一個嵌套JSON結構代表一棵樹,它看起來是這樣的:

[{ 
    "name": "flare", 
    "root": "true", 
    "children": [ 
    { 
    "name": "analytics", 
    "nestedproperties": [ 
     { "attribute": "attribute1", 
      "type": "type1" }, 
     { "attribute": "attribute2", 
      "type": "type2" }, 
     { "attribute": "attribute3", 
      "type": "type3" } 
    ], 
    "children": [ 
     { 
     "name": "cluster", 
     "nestedproperties": [ 
      { "attribute": "attribute4", 
       "type": "type4"}, 
      .... 
     ] 
     }, 
    ... 

除了與節點和他們的孩子顯示正常的樹結構,我要代表nestedproperties下,每個元件都鏈接到他們的父節點的圈子。

通過以下的答案我管理通過使嵌套數據作爲參數來.data(),以顯示每個的nestedproperties元素如this question建議其它一些問題,並在其它實例。代碼的核心部分是這樣的:

var pii = nodeEnter.selectAll("circle.pii") 
     .data(function(d) {return d.nestedproperties; }) 


    var piiEnter = pii.enter().append("svg:g") 
     .attr("class", "piinode") 
     .attr("transform", "translate(50,50)") 
     //.attr("transform", function(d, i) { return "translate(" + d.x + "," + d.y + ")"; }) // <<--- I cannot call this function because d.x and d.y does not exist 
     .call(forcepii.drag); 

    // Append the circle for the node 
    piiEnter.append("svg:circle") 
     .attr("class", "pii") 
     .attr("r", 25) 
     .style("fill", "blue") 
     .style("stroke", "#999999") 

完整的代碼是在這個jsfiddle

問題是,代表嵌套屬性內的元素的圓圈全部相互疊加顯示,無法拖動。我不明白如何將force.nodes()應用於嵌套元素或如何使用transform屬性對它們進行滴答。

嘗試以下告訴我「遺漏的類型錯誤:無法設置的未定義的屬性‘指數’」

forcepii.nodes(function(d) { return d.nestedproperties; }) 
    //.links(links) 
    .gravity(0.05) 
    .charge(-1500) 
    .linkDistance(100) 
    .friction(0.5) 
    .linkStrength(function(l, i) {return 1; }) 
    .size([w, h]) 
    //.on("tick", tick) 
    .start(); 

這裏是拍攝的圖像。正如你所看到的圓上彼此力量的頂部繪製並未被應用於:

enter image description here

感謝您的幫助!

回答

1

最後我發現這是如何完成的。這裏是表示活生生的例子一個要點:http://bl.ocks.org/djjupa/5655723

由於我的數據是「靈活」我重新編碼它有「孩子」元素嵌套的選擇,所以它看起來是這樣的:

[{ 
    "name": "flare", 
    "root": "true", 
    "children": [ 
    { 
    "name": "analytics", 
    "nestedproperties": { 
     "children": [ 
       { "attribute": "attribute1", 
       "type": "type1" }, 
       { "attribute": "attribute2", 
       "type": "type2" }, 
       { "attribute": "attribute3", 
       "type": "type3" } 
      ] 
    }, 
    "children": [ 
     { 
     "name": "cluster", 
     "nestedproperties": { 
       "children": [ 
        { "attribute": "attribute4", 
        "type": "type4" 
        }, 
         .... 
       ] 
     } 
     }, 
    ...