我有一个像这样的 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');
但现在我想要一个基于性别的“编程”的单独方法。对于女性和男性来说也是如此。 我该怎么做?
最佳答案
// 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);
关于javascript - 使用 d3.js 计算平均 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585967/