Search code examples
javascriptjsond3.jsdata-virtualization

d3.js json structure add data


I'm drawing a pie chart with two simple values: label and value. This is my json:

{
"valuecase": {
    "times": [
        {"label": "label", "value":5},
        {"label": "label", "value":13}
    ],
    "record": [
        {"label": "label", "value":5},
        {"label": "label", "value":13}
    ]
}

}

I'm not sure it's the best structure, in fact d3.js I can't call data value. This is my code:

d3.json("my.json", function(json) {
data = json.valuecase;
...selectAll("path")
.data(pie(dataset.times)) //*** How call the array, only value data??
}

any suggestions?


Solution

  • You need to pass an array of values to the pie()... You can try d3.layout.pie().value(function(d) {return d.value; }); ...

    d3.json("myjson.json", function(json) {
    
        var data = json.valuecase
    
        var w = 300,                           
        h = 300,   
        r = 100, 
        color = d3.scale.category20c();         
    var vis = d3.select("body")
    .append("svg:svg")             
    .data([data.times])                   
    .attr("width", w)
    .attr("height", h)
            .append("svg:g")                
            .attr("transform", "translate(" + r + "," + r + ")")    
    
            var arc = d3.svg.arc()              
            .outerRadius(r);
    
    var pie = d3.layout.pie()                   
      .value(function(d) { console.log(d); return d.value; });    
    var arcs = vis.selectAll("g.slice")     
      .data(pie)                          
      .enter()        
      .append("svg:g")        
      .attr("class", "slice");
    arcs.append("svg:path")
      .attr("fill", function(d, i) { return color(i); } ) 
      .attr("d", arc);                                
    arcs.append("svg:text")                                     
      .attr("transform", function(d) {                    
                d.innerRadius = 0;
                d.outerRadius = r;
                return "translate(" + arc.centroid(d) + ")";        
            })
    .attr("text-anchor", "middle")                                      
      .text(function(d, i) { return data.times[i].value; });        
    });