用d3.js计算平均值json

时间:2012-11-27 14:05:19

标签: javascript json d3.js mean

我有一个像这样的json文件:

[
 {"id":1,"sex":"Female","programming":5, "project":7}, 
 {"id":2,"sex":"Male","programming":8, "project":4}, 
 {"id":3,"sex":"Female","programming":5, "project":6}, 
 {"id":4,"sex":"Male","programming":4, "project":7} 
]

我想用D3 js计算编程值的平均值 我可以这样得到它的总平均值:

function meanVak(value) {
    return d3.mean(data, function(d) {return d [value] })
}

var meanProgramming = meanVak('programming');

但现在我想要一个基于性别的“编程”单独的意思。对于女性和男性。 我该怎么做?

2 个答案:

答案 0 :(得分:1)

// I think the easiest way is to use the d3.nest function.  Perhaps something like ... 
var nest = d3.nest()
  .key(function(d) { return d.sex; })
  .sortKeys(d3.ascending)
  .rollup(function(d) {
    return {
      meanVakValue: d3.mean(d, function(g) { return g[value]; })
    };
  })
  .map(data);

// You may then need to turn it back into entries.  I had to use map first then extract to entries
// but I'm still getting my head around d3.
var nestedData = d3.entries(nest);

答案 1 :(得分:0)

在我看来,您需要创建一个仅包含Females / Males的新数组,然后将该函数与新数组一起使用,您可以使用jquery.map()轻松创建新数组。

查看HERE示例。

var data = [
 {"id":1,"sex":"Female","programming":5, "project":7}, 
 {"id":2,"sex":"Male","programming":8, "project":4}, 
 {"id":3,"sex":"Female","programming":5, "project":6}, 
 {"id":4,"sex":"Male","programming":4, "project":7} 
];

var newArray = $.map(obj,function(elem){
  return elem.sex === 'Female'? elem :null;
});