javascript - d3.js : time scale and data : gape of some pixel between tick and data

标签 javascript d3.js axis timeline

我的时间 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/

相关文章:

javascript - 如何从 Composition API 中的 Axios Response 返回变量到根级别?

javascript - d3.js 和 csv 文件图形宽度的数据可视化

javascript - 为什么要从标签名称中删除空格?

java - 执行 Web 服务客户端时出错

java - 如何从 axis1 stub 获取传输的响应 header

javascript - 如何将可更新的 `this` 从静态方法传递给静态方法?

javascript - 将 id 传递到 url 以获取 angular.js 中的单个 View

javascript - Angular : Show div content depending on 2 stage drop down menu

javascript - 如何保持 d3.forceSimulation() 节点均匀分布而不重叠

r - 如何使用 ggplot 在 x Axis 上添加更多标签