[英]time.ticks doesn't output the correct dates
My code is as follows 我的代码如下
const xScale = scaleTime()
.domain([new Date(reports[reports.length - 1].date), new Date(reports[0].date)])
.range([margin.left, width]
where the domain is the date 2018-02-25 to 2018-03-03 域名是日期2018-02-25至2018-03-03
I want my x axis to show the 7 days: Sun 25, Mon 26, Tues 27, Wed 28, Thu 1, Fri 2, Sat 3 我希望我的x轴显示7天:星期日25,星期一26,星期二27,星期三28,星期四1,星期五2,星期六3
So i use d3's .ticks to get these tickvalues 所以我用d3的.ticks来获取这些滴答值
const ticksX = xScale.ticks(timeDay, 1)
However what I get is 6 days: Sun 25, Mon 26, Tues 27, Wed 28, Thu 1, Fri 2 但是我得到的是6天:星期日25,星期一26,星期二27,星期三28,星期四1,星期五2
So I tried to increment my right domain by 1 with momentjs: 所以我试图用momentjs将我的正确域增加1:
moment(new Date(reports[0].date)).add(1, 'days')
INSTEAD I get 8 days: Sun 25, Mon 26, Tues 27, Wed 28, Thu 1, Fri 2, Sat 3, Mon 4 INSTEAD我有8天:星期日25,星期一26,星期二27,星期三28,星期四1,星期五2,星期六3,星期一4
What is going on here? 这里发生了什么? I can't find the pattern.
我找不到模式。
Specifying the exact ticks in a time scale is sometimes difficult and maybe frustrating in a D3 code. 在时间范围内指定准确的滴答有时会很困难,并且可能在D3代码中令人沮丧。 However, this is by design: time scales are complex and they are supposed to automatically generate the adequate ticks.
但是,这是设计使然的:时间尺度很复杂,应该自动生成足够的刻度。 It becomes even more complicated in your case because there is the hour issue (which is supposed to be midnight, but that's not guaranteed) and the timezone.
在您的情况下,它变得更加复杂,因为存在小时问题(应该是午夜,但这不能保证)和时区。
There are several different solutions to get your 7 ticks. 有几种不同的解决方案可以使您获得7分。
The first one is setting the hour to midnight: 第一个是将时间设置为午夜:
const xScale = d3.scaleTime() .domain([new Date("2018-02-25").setHours(0, 0, 0, 0), new Date("2018-03-03").setHours(0, 0, 0, 0)]); const ticksX = xScale.ticks(d3.timeDay, 1); console.log(ticksX);
<script src="https://d3js.org/d3.v4.min.js"></script>
Another solution is using D3 timeParse
: 另一个解决方案是使用D3
timeParse
:
const timeParse = d3.timeParse("%Y-%m-%d") const xScale = d3.scaleTime() .domain([timeParse("2018-02-25"), timeParse("2018-03-03")]); const ticksX = xScale.ticks(d3.timeDay, 1); console.log(ticksX);
<script src="https://d3js.org/d3.v4.min.js"></script>
Finally, another solution is using nice()
: 最后,另一种解决方案是使用
nice()
:
const xScale = d3.scaleTime() .domain([new Date("2018-02-25"), new Date("2018-03-03")]) .nice(); const ticksX = xScale.ticks(d3.timeDay, 1); console.log(ticksX);
<script src="https://d3js.org/d3.v4.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.