[英]d3 range/domain returning negative values?
I have this array: 我有这个数组:
var bucket_contents = [8228, 21868, 12361, 15521, 3037, 2656];
I am trying to alter the width of a series of rect
s based on these values using range/domain. 我正在尝试根据这些值使用范围/域来更改一系列rect
的宽度。 This is my code: 这是我的代码:
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');
Currently the console log bucket_width(i)
inside the forEach loop outputs the following: 当前,forEach循环中的控制台日志bucket_width(i)
输出以下内容:
-138.24692900270665
-138.1948782011243
-138.14282739954194
-138.09077659795963
-138.03872579637726
-137.98667499479492
Console log on d3.min(..)
is 2656 and d3.max(..)
is 21868 as expected. 控制台登录d3.min(..)
是2656, d3.max(..)
是21868。
What am I doing wrong? 我究竟做错了什么? I thought range 'normalizes' any values within that range, ie 21868 would return 1000 and 2656 would return 0. 我认为范围会“标准化”该范围内的任何值,即21868将返回1000,而2656将返回0。
Your problem is that you are calling bucket_width(i)
instead of bucket_width(d)
. 您的问题是您正在调用bucket_width(i)
而不是bucket_width(d)
。 Hence, you are passing in values of 0
, 1
, etc. which are less than the min
value of 2656 by quite some. 因此,要传递的值中的0
, 1
等,其是小于所述min
通过相当长的一段的2656值。
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) );
});
Output: 输出:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.