2016-01-23 67 views
0

我建立一個餅圖,我的數據是JSON形式:如何將對象數組綁定到D3餅圖中的弧?

[ 
    { 
    "Stage":"birth", 
    "Avg":19071 
    }, 
{ 
    // 
} 
] 

我不知道我應該怎麼使用數據功能到JSON數據綁定到我的選擇。所以,這不是爲我工作:

pie = d3.layout.pie(); 

arcs = svg.selectAll("g.arc") 
    .data(pie(data)) // ? 
    .enter() 
    .append("g") 
    .attr({ 
    "transform" : "translate(" + outerRadius + "," + outerRadius + ")", 
    "class": function(d,i){ 
     console.log(d3.keys(d)); 
    }  
    }); 

pie.sort(null); 

//Draw arc paths 
arcs.append("path") 
    .attr({ 
    "d": arc, 
    "class" : "arc" 
    }); 

如何使用。數據這樣我就可以有機會獲得在JSON每個鍵/值對?對不起,如果這是一個非常簡單的問題,但我不能圍繞在這種情況下鍵的工作方式。

+0

以前意味着你哈瓦像[1970年,1971年...] ..就像現在你有[{XXX數據:1970,xxx:'sdafsdf'},{......}] ...對嗎? – saikumar

+0

@saikumar是這就像[{xxx:1970,xxx:'sdafsdf'},{......}]。我習慣於在D3中使用平面數組。爲了清晰起見,我會編輯我的措詞。謝謝 – Benjamin

回答

3

你需要給你的layout.pie一個value accessor函數。

var pie = d3.layout 
    .pie() 
    .sort(null) 
    .value(function(d){ 
    return d.Avg; //<-- d3 will pie the values in Avg property 
    }); 

全部工作示例:

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script src="script.js"></script> 
 
</head> 
 

 
<body> 
 
    <script> 
 
    var data = [{ 
 
     "Stage": "birth", 
 
     "Avg": 19071 
 
    }, { 
 
     "Stage": "death", 
 
     "Avg": 10000 
 
    }]; 
 
    
 
    var svg = d3.select('body') 
 
     .append('svg') 
 
     .attr('width', 500) 
 
     .attr('height', 500); 
 
     
 
    var colors = d3.scale.category10(); 
 

 
    var pie = d3.layout 
 
     .pie() 
 
     .sort(null) 
 
     .value(function(d) { 
 
     return d.Avg; 
 
     }) 
 

 
    var arc = d3.svg.arc() 
 
     .outerRadius(90) 
 
     .innerRadius(0); 
 

 
    var arcs = svg.selectAll("g.arc") 
 
     .data(pie(data)) //<-- this is fine 
 
     .enter() 
 
     .append("g") 
 
     .attr({ 
 
     "transform": "translate(" + 100 + "," + 100 + ")", 
 
     "class": function(d, i) { 
 
      return d.data.Stage; //<-- after pieing the data, the raw data is then in the data property 
 
     } 
 
     }); 
 

 
    //Draw arc paths 
 
    arcs.append("path") 
 
     .attr({ 
 
     "d": arc, 
 
     "class": "arc" 
 
     }) 
 
     .style('fill', function(d,i){ 
 
     return colors(i); 
 
     }) 
 
    </script> 
 
</body> 
 

 
</html>