2016-04-25 23 views
1

我想正確包裝我的氣泡圖項目(我改變了尺寸,這要感謝我的JSON值.attr("r", function(d) { return d.size; })),如果我有很多氣泡,它們會重疊。碼頭上的.pack()方法,但我不使用正確的話,我不知道如何使用它根據圓圈大小包裝氣泡圖

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 
    text { 
     font: 10px sans-serif; 
    } 
</style> 
<body> 
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> 
<script> 

    var diameter = 960, 
      format = d3.format(",d"), 
      color = d3.scale.category20c(); 

    var bubble = d3.layout.pack() 
      .sort(null) 
      .size([diameter, diameter]) 
      .padding(1.5); 

    var svg = d3.select("body").append("svg") 
      .attr("width", diameter) 
      .attr("height", diameter) 
      .attr("class", "bubble"); 


    d3.json("./data.json", function(error, root) { 
     if (error) throw error; 

     var node = svg.selectAll(".node") 
       .data(bubble.nodes(classes(root)) 
       .filter(function(d) { return !d.children; })) 
       .enter().append("g") 
       .attr("class", "node") 
       .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); 

     node.append("title") 
       .text(function(d) { return d.className + ": " + format(d.value); }); 

     node.append("circle") 
       .attr("r", function(d) { return d.size; }) 
       .style("fill", function(d) { return color(d.size); }); 

     node.append("text") 
       .attr("dy", ".3em") 
       .style("text-anchor", "middle") 
       .text(function(d) { return d.className.substring(0, d.r/3); }); 

    }); 

    // Returns a flattened hierarchy containing all leaf nodes under the root. 
    function classes(root) { 
     var classes = []; 
     function recurse(name, node) { 
      if (node.children) node.children.forEach(function(child) { recurse(node.name, child); }); 
      else classes.push({packageName: name, className: node.name, value: node.size, size: node.size}); 
     } 
     recurse(null, root); 
     return {children: classes}; 
    } 
    d3.select(self.frameElement).style("height", diameter + "px"); 

</script> 
</body> 

這是項目Plunker:https://plnkr.co/edit/PjN6v3dr2yP3oST5sCTB?p=preview

回答

1

而是這行:

.attr("r", function(d) {return d.size; }) 

使用d.r由所述氣泡產生的包:

.attr("r", function(d) {return d.r; }) 

更新plnkr:https://plnkr.co/edit/ao9RbxOKQ7VuobzOsVJd?p=preview

+0

氣泡包知道的大小將它傳遞到在遞歸函數的值:值:node.size – thatOneGuy

+0

好的,謝謝它的作品! '.attr(「r」,function(d){return dr;})'在原始示例中,所以我不明白屬性是什麼:'.value(function(d){console.log(d .size); return d.size;})' – Anonyme