2012-11-22 17 views
1

在JavaScript中,我如何變換一個「長表的格式」的數據結構適合於線圖:線圖系列的對象數組? (+爲Crossfilter溶液)

var data = [ 
    {"type":"A"," year":2000," value":50}, 
    {"type":"A"," year":2001," value":51}, 
    {"type":"A"," year":2002," value":52}, 
    {"type":"B"," year":2000," value":60}, 
    {"type":"B"," year":2001," value":55}, 
    {"type":"B"," year":2002," value":57} 
] 

=> 

var series = [ 
    {type: "A", values : [{x: 2000, y: 50}, {x: 2001, y: 52},] }, 
    {type: "B", values : [{x: 2000, y: 60}, {x: 2001, y: 55},] }, 
] 

香草JavaScript解決方案以及與所述Crossfilter的溶液庫 - 可以在任何維度的數據上工作 - 將是有價值的: https://github.com/square/crossfilter/wiki/API-Reference

回答

1

好問題,但不是直截了當; )

看一看https://github.com/NickQiZhu/dc.js/pull/91

你會碰到這樣的:

cr = crossfilter(data); 
typeDim=cr.dimension(function(d) {return d.type}); 
typeGroup=typeDim.group(); 

yearDim=cr.dimension(function(d) {return d.year}); 
valDim=cr.dimension(function(d) {return d.value}); 

yearTypeGroup = dateDimension.group(); 
yearTypeGroup.reduce( 
    // add 
    // pivot[0].idx()[i] returns the index of statusGroup 
    // the reduce function hence construct a key-value object, keys being indexes of the pivot group. 
    function(p, v, i, pivot) { 
     ++p[pivot[0].idx()[i]].count; 
     p[pivot[0].idx()[i]].value += +v.value; 
     return p; 
    }, 
    //remove 
    function(p, v,i,pivot) { 
     --p[pivot[0].idx()[i]].count; 
     p[pivot[0].idx()[i]].value -= +v.value; 
     return p; 
    }, 
    //init 
    function(pivot) { 
     var l, i, obj ={}; 
     if(l = pivot[0].all().length){ 
      for(i=0; i<l; ++i) { 
       obj[i] = {count:0, value:0} 
      } 
     } 
     return obj 
    } 
); 

yearTypeGroup.pivot(typeGroup) 

運氣好; ) C.

+0

感謝分享! d3.nest方法也很整潔,但我很高興學習如何對crossfilter進行相同操作。 – dani

+0

你是對的,d3.nest對此也可能有用,但是你必須在每次交叉過濾後重新嵌套。使用上述方法,您的圖表系列將即時反映交叉過濾器分組和過濾。 – krikrou

+0

啊,聰明。謝謝! – dani