2015-10-27 27 views
1

嘗試修改下面鏈接的代碼以創建一個動畫分散圖,顯示隨時間推移的數據點。Javascript - 數據插值 - D3動畫散點圖

http://bost.ocks.org/mike/nations/

掙扎到包裹我的頭周圍的數據內插部

// Interpolates the dataset for the given (fractional) year. 
     function interpolateData(year) { 
     return nations.map(function(d) { 
      return { 
      employee: d.employee, 
      category: d.category, 
      x:interpolateValues(d.x, year), 
      y:interpolateValues(d.y, year) 
      }; 
     }); 
     } 

     // Finds (and possibly interpolates) the value for the specified year. 
     function interpolateValues(values, year) { 
     var i = bisect.left(values, year, 0, values.length - 1), 
      a = values[i]; 
     if (i > 0) { 
      var b = values[i - 1], 
       t = (year - a[0])/(b[0] - a[0]); 
      return a[1] * (1 - t) + b[1] * t; 
     } 
     return a[1]; 
     } 
    }); 

代碼被以這種格式期待數據,用含有與相應的年和值的陣列的X和Y值。

d: Object 
category: "1" 
employee: "12017512" 
x: Array[63] 
y: Array[63] 

我通過的數據是這種格式,每年的記錄。

d: Object 
category: "1" 
employee: "12017512" 
x: 2697.3199999999993 
y: 24 
year: "2015" 

如何修改代碼以接受我擁有的格式的數據?

回答

0

管理解決我的問題。答案是否可以幫助任何人使用underscore.js和下面的代碼。

我還發現以下jsfiddle很有幫助。

http://jsfiddle.net/bgAzH/1/

groupData = _.map(_.groupBy(data, 'dimension1', 'dimension2'), function (b) { 
      return _.extend(_.pick(b[0], 'dimension1', 'dimension2'), { 
       x: _.map(b, function (elem) { 
        return _.pick(elem, 'time', 'x') 
       }), 
       y: _.map(b, function (elem) { 
        return _.pick(elem, 'time', 'y') 
       }) 
      }); 
     }); 

然後傳遞對象的陣列到插補值的函數,當我轉換的對象以簡單陣列。

var values = values.map(function (obj) { return [Number(obj.time), obj[element]]});