我有这个代码:https://plnkr.co/edit/t1GKaQOGnFxkTMK03Ynk
var MIN = 60;
var HR = MIN * 60;
var tripDomain = [0, 15*MIN, 30*MIN, 45*MIN, 60*MIN, 90*MIN, Math.max(24*HR, d3.max(data))];
var bins = d3.histogram()
.thresholds(tripDomain)(data);
var x = d3.scaleOrdinal()
.domain(tripDomain)
.range(tripDomain.map((_,i) => (i/(tripDomain.length-1))*width));
// ...more code...
chart.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
正确呈现直方图。唯一的问题是 Axis 的第一个刻度将 0 和 61 绘制在彼此之上。它应该只有 0...不确定 61 是从哪里来的(它是数据的第一个值),但我不知道它是如何在 Axis 上结束的。
注意 Axis 上的第一个值...您能阐明这个问题吗?
最佳答案
...not sure where the 61 is coming from.
它来自比例域,当您附加矩形和文本时,您正在更改它!这是预期的行为,因为您使用的是序数标度。
说明:
您的 x 尺度域定义明确:
[0, 900, 1800, 2700, 3600, 5400, 1280703]
但是,在您的第一个 bin 中,您有这个(作为数组属性):
[x0: 61, x1: 900]
因此,每当您使用带有 x 标度的第一个 bin 的 x0
时,例如:
.attr("transform", function(d){
return "translate(" + x(d.x0) + "," + y(d.length) + ")";
});
...您实际上是在域中引入一个新值(有关详细说明,请参阅我的 answer here ),因为没有 61
x 尺度域。
顺便说一句,这个新值是在域的末尾引入的,尽管非常接近0
,但61
实际上是最后一个滴答声。
解决方案:
声明未知
:
var x = d3.scaleOrdinal()
.unknown(0)
这是您更新的插件:https://plnkr.co/edit/n1IoEkHcL0sGUraDVCfc?p=preview
关于javascript - D3 条形图 Axis 怪癖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42588929/