我有这个数组:
var bucket_contents = [8228, 21868, 12361, 15521, 3037, 2656];
我正在尝试使用范围/域根据这些值更改一系列矩形
的宽度。这是我的代码:
var bucket_width = d3.scale.linear()
.domain([d3.min(bucket_contents), d3.max(bucket_contents)])
.range([0, 1000]);
bucket.forEach(function(d, i) {
d.x = (width / bucket.length) * i;
d.y = (height / 2) - 25;
d.w = bucket_width(i);
console.log(bucket_width(i));
});
d3.select("#plot").selectAll(".bucket")
.data(bucket)
.enter()
.append("rect")
.attr("class", "bucket")
.attr("x", function(d, i) { return d.x; })
.attr("y", function(d, i) { return d.y; })
.attr('width', function(d, i) { return d.w; })
.attr('height', '50')
.style("fill", '#000');
当前 forEach 循环内的控制台日志 bucket_width(i)
输出以下内容:
-138.24692900270665
-138.1948782011243
-138.14282739954194
-138.09077659795963
-138.03872579637726
-137.98667499479492
d3.min(..)
上的控制台日志为 2656,d3.max(..)
与预期一致,为 21868。
我做错了什么?我认为范围“标准化”该范围内的任何值,即 21868 将返回 1000,2656 将返回 0。
最佳答案
您的问题是您正在调用 bucket_width(i)
而不是 bucket_width(d)
。因此,您传入的值是 0
、1
等,这些值比 min
值 2656 小很多。
演示:http://jsfiddle.net/2tq8S/
var contents = [8228, 21868, 12361, 15521, 3037, 2656];
var bucket_width = d3.scale.linear().domain(d3.extent(contents)).range([0, 1000]);
contents(function(d, i){
console.log( d, i, bucket_width(i), bucket_width(d) );
});
输出:
8228 0 -138.24 290.03
21868 1 -138.19 1000.00
12361 2 -138.14 505.15
15521 3 -138.09 669.63
3037 4 -138.03 19.83
2656 5 -137.98 0.00
关于javascript - d3 范围/域返回负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367251/