使用json进行D3嵌套选择:如何将.force()应用于嵌套元素?

时间:2013-05-11 23:11:27

标签: json graph d3.js force-layout

(这是一个问题here的后续问题。这个问题尚未完全解决,这是一个延续,所以我发布一个新问题)

我有一个表示树的嵌套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下的每个元素表示链接到其父节点的圆圈。

通过跟踪其他一些问题和其他示例的答案,我设法通过将嵌套数据作为参数传递给nestedproperties来显示.data()的每个元素,如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属性进行滴答。

尝试以下内容告诉我“未捕获的TypeError:无法设置未定义的属性'索引”

   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 个答案:

答案 0 :(得分: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"
                   },
                      ....
               ]
         }
      },
  ...