我的时间 Axis 有问题,所以我在网上搜索,发现网上的教程/示例也有同样的问题:(
关于这个 fiddle http://jsfiddle.net/lampalork/dm6ff3ua/ (这只是 fiddle 上找到的示例的一个分支)
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format('%a %d'))
.tickSize(5)
.tickPadding(8);
svg.selectAll('.chart')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', function(d) { return x(new Date(d.date)); })
你可以看到问题,如果你查看时间 Axis 和第一个条形图,你可以看到 3-4 像素的间隙。我在工作中遇到了同样的问题,并且我在网络的其他示例上看到了这个问题。任何想法 ?谢谢
最佳答案
这一行:
.attr('x', function(d) { return x(new Date(d.date)); })
正在使用 UTC 时区创建日期对象。来自 Mozilla :
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).
d3
不过使用本地时区来绘制刻度。
改为以 d3 方式执行所有操作并使用 d3.time.format 。在我的时区,差异如下:
new Date("2012-03-20")
> Mon Mar 19 2012 20:00:00 GMT-0400 (Eastern Daylight Time)
d3.time.format('%Y-%m-%d').parse("2012-03-20")
> Tue Mar 20 2012 00:00:00 GMT-0400 (Eastern Daylight Time)
已更新fiddle .
关于javascript - d3.js : time scale and data : gape of some pixel between tick and data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357906/