我不确定为什么d3.min()和d3.max()最后会返回相同的结果。这是代码:
var groupByAgeAndtime = d3.nest()
.key(function(d) { return d.age; })
//.key(function(d) { return d.time_in_hospital; })
.rollup(function(v) {
return{
mean_time_in_hospital : d3.mean(v, function(d){ return d.time_in_hospital;})
} })
.object(datapoints);
console.log(groupByAgeAndtime);
var radiusScale = d3.scaleSqrt().domain([d3.min(Object.keys(groupByAgeAndtime), function(d){
return groupByAgeAndtime[d];//minimum average time spent
}),d3.max(Object.keys(groupByAgeAndtime), function(d){
return groupByAgeAndtime[d];//maximum average time spent
})]).range([50,150])
console.log('Min: ',d3.min(Object.keys(groupByAgeAndtime), function(d){
return groupByAgeAndtime[d];//manimum average time spent
}));
console.log('Max: ',d3.max(Object.keys(groupByAgeAndtime), function(d){
return groupByAgeAndtime[d];//maximum average time spent
}));
这是Mozilla Firefox中控制台的屏幕截图: Screenshot
这是我的jsfiddle的链接:Link
有人可以向我解释为什么会这样吗?我在代码中哪里做错了?
答案 0 :(得分:0)
Object.keys
返回给定对象自己的属性名称的数组。
Object.keys(groupByAgeAndtime) // return Array(3) [ "0-10", "10-20", "20-30" ]
当访问器函数返回groupByAgeAndtime[d]
时,您将获得每个键的值:
{ mean_time_in_hospital: 1 }
{ mean_time_in_hospital: 2 }
{ mean_time_in_hospital: 6 }
...
正如 @jrook 所指出的那样,您的函数将基于该对象中的键来获得最小/最大,这始终是相同的:mean_time_in_hospital
。
您想要keys
而不是对象中的values
,然后返回mean_time_in_hospital
键的值。
var groupByAgeAndtime = {
"0-10": {
mean_time_in_hospital: 1
},
"10-20": {
mean_time_in_hospital: 2
},
"20-30": {
mean_time_in_hospital: 6
},
};
console.log('Min: ', d3.min(Object.values(groupByAgeAndtime), function(d) {
return d.mean_time_in_hospital; //manimum average time spent
}));
console.log('Max: ', d3.max(Object.values(groupByAgeAndtime), function(d) {
return d.mean_time_in_hospital; //maximum average time spent
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>