如何使用日期对象作为直线轴的刻度标签

How can I use date objects as tick labels for a linear axis?

本文关键字:标签 日期 何使用 对象      更新时间:2023-09-26

我尝试过使用d3时间轴,是的,这个问题是通过使用d3时间轴来解决的,但还有很多其他的复杂性我无法处理。另一方面,线性轴似乎只表示打勾标签的问题。

我有一个充满日期对象的数组为我的标记- dateTickValues

console.log(dateTickValues)

返回
Thu Jan 01 2015 05:30:00 GMT+0530 (IST),Fri Jan 02 2015 05:30:00 GMT+0530 (IST),Sat Jan 03 2015 05:30:00 GMT+0530 (IST),Sun Jan 04 2015 05:30:00 GMT+0530 (IST),Mon Jan 05 2015 05:30:00 GMT+0530 (IST),Tue Jan 06 2015 05:30:00 GMT+0530 (IST)

但是当我使用

var xScale = d3.scale.linear()
.domain([0, no_of_ticks])
.range([0, width]);

var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(no_of_ticks) //computed elsewhere in the code - clean
.tickValues(dateTickValues)
.orient("top");

结果图上的勾号标签为空-即不出现勾号标签。

为什么会发生这种情况,我该如何修复它?

关键是使用.tickFormat()函数。我不清楚你到底想做什么,所以这里有两个版本。

首先,您可以使用Date对象本身的比例,然后.tickFormat()类似于

.tickFormat(function(d) { return d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(d)); });

完整的演示在这里。

如果你使用的是一个带有刻度的日期数组的索引,它应该是类似于

.tickFormat(function(d, i) { return d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(dates[i])); });

完整的演示在这里。

另一方面,同时使用.ticks().tickValues()是没有意义的——您可能只需要.tickValues()