2016-07-15 120 views
0

有沒有選項可以聚合C3圖表中的數據?當JSON包含具有相同類別的多個數據元素時,數據在圖表中被繪製爲多個點,因爲它應該彙總並顯示爲圖表中的單個點。 附上C3圖表和預期圖表格式。 在該示例中:「名稱1」在300處顯示單點爲上載,其中作爲離子C3它在200處顯示一個點,而在另一個點顯示爲100。c3js中的數據聚合

代碼中使用:

var chart = c3.generate({ 
      bindto:'#png-container', 
      data: { 
       json: [ 
       {name: 'name1', upload: 200, download: 200, total: 400}, 
       {name: 'name1', upload: 100, download: 300, total: 400}, 
       {name: 'name2', upload: 300, download: 200, total: 500}, 
       {name: 'name3', upload: 400, download: 100, total: 500}, 
       ], 
       keys: { 
       x: 'name', // it's possible to specify 'x' when category axis 
       value: ['upload', 'download'], 
       }, 
       groups: [ 
       ['name'] 
       ] 
      }, 
      axis: { 
       x: { 
       type: 'category' 
       } 
      } 
     }); 

上面的代碼的輸出: enter image description here

預期輸出:

enter image description here

回答

1

沒有內置C3據我所知。您可以使用d3的嵌套運算符來聚合json數據,然後再將它傳遞給c3。

var json = [ 
      {name: 'name1', upload: 200, download: 200, total: 400}, 
      {name: 'name1', upload: 100, download: 300, total: 400}, 
      {name: 'name2', upload: 300, download: 200, total: 500}, 
      {name: 'name3', upload: 400, download: 100, total: 500}, 
      ]; 

    var agg = function (json, nestField) { 
     var nested_data = d3.nest() 
      .key(function(d) { return d[nestField]; }) 
      .rollup(function(leaves) { 
       // Work out the fields we're not nesting by 
       var keys = d3.merge (leaves.map (function(leaf) { return d3.keys(leaf); })); 
       var keySet = d3.set(keys); 
       keySet.remove (nestField); 
       var dataFields = keySet.values(); 

       // total these fields up 
       // console.log(leaves, dataFields); // just for testing 
       var obj = {}; 
       dataFields.forEach (function (dfield) { 
        obj[dfield] = d3.sum(leaves, function(d) {return d[dfield];}); 
       }); 
       return obj; 
      }) 
      .entries(json); 

     // return to original json format 
     var final_data = nested_data.map (function(nestd) { 
      nestd.values[nestField] = nestd.key; 
      return nestd.values; 
     }); 

     return final_data; 
    }; 

    var chart = c3.generate({ 
     bindto:'#png-container', 
     data: { 
      json: agg(json, "name"), 
      keys: { 
      x: 'name', // it's possible to specify 'x' when category axis 
      value: ['upload', 'download'], 
      }, 
      groups: [ 
      ['name'] 
      ] 
     }, 
     axis: { 
      x: { 
      type: 'category' 
      } 
     } 
    }); 

https://jsfiddle.net/8uofn7pL/2/

哎呦,鏈接到錯誤的小提琴有