2014-05-11 60 views
1

我对D3有点新,但仍然有一些理解它的问题。D3 - 圆圈包装多个数据

我使用本教程Zoomable Circle Packing

不过,我不知道如何加载多个数据集。例如,我需要类似于(you can see on jsfiddle)的东西,但是当按下按钮时,会加载一个不同的.JSON文件(两个文件中的名称相同,但值不同)。

解决方案可能是mbostock的“Thinking with Joins”,但我真的不知道如何使用它。

任何帮助,将不胜感激。

回答

1

您可以使用函数来调用JSON文件加载这样的:

var callJson = function (json) { 
    d3.json(json, function(error, root) { 
    if (error) return console.error(error); 

    svg.selectAll("circle").remove(); 
    svg.selectAll("text").remove(); 

    var focus = root, 
     nodes = pack.nodes(root), 
     view; 

    var circle = svg.selectAll("circle") 
     .data(nodes) 
     .enter().append("circle") 
     .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) 
     .style("fill", function(d) { return d.children ? color(d.depth) : null; }) 
     .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); }); 

    var text = svg.selectAll("text") 
     .data(nodes) 
     .enter().append("text") 
     .attr("class", "label") 
     .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) 
     .style("display", function(d) { return d.parent === root ? null : "none"; }) 
     .text(function(d) { return d.name; }); 

    var node = svg.selectAll("circle,text"); 

    d3.select("body") 
     .style("background", color(-1)) 
     .on("click", function() { zoom(root); }); 

    zoomTo([root.x, root.y, root.r * 2 + margin]); 

    function zoom(d) { 
     var focus0 = focus; focus = d; 

     var transition = d3.transition() 
      .duration(d3.event.altKey ? 7500 : 750) 
      .tween("zoom", function(d) { 
      var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]); 
      return function(t) { zoomTo(i(t)); }; 
      }); 

     transition.selectAll("text") 
     .filter(function(d) { return d.parent === focus || this.style.display === "inline"; }) 
      .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) 
      .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) 
      .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); 
    } 

    function zoomTo(v) { 
     var k = diameter/v[2]; view = v; 
     node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; }); 
     circle.attr("r", function(d) { return d.r * k; }); 
    } 
    }); 
}; 

...然后你callJson("flare.json");

这里正在与多个JSON文件的例子称之为 - http://bl.ocks.org/chule/74e95deeadd353e42034

+0

Thx快速响应,这是完美的! :) – Ficho

+0

另外,我必须补充一点,我不希望收到与我住在同一个城市的人的回答。波兹拉夫是奥西耶卡(学生ETF-a)。 – Ficho

+0

大声笑,我从来没有料到将来自我的小镇的人回答了stackoverflow/d3的问题。干杯! – cuckovic