简体   繁体   English

即使我将刻度间隔设置为每7天,为什么我的d3图表的x轴将每个月的第一天都作为刻度显示?

[英]Why does my d3 chart's x-axis include the first of every month as a tick even though I set the tick interval to every 7 days?

I am new to d3 but I have set the tick interval for my x-axis to every 7 days using d3.timeDay.every(7) . 我是d3的新手,但是我已经使用d3.timeDay.every(7) x轴的刻度间隔设置为每7天一次。 However when my graph is created, I also see a tick mark added for the first of every month. 但是,在创建图形时,我还会看到每个月的第一天添加了一个勾号。 For example, my graph shows ticks at 10/1, 10/8, 10/15, 10/22, 10/29, and 11/1, even though 11/1 is not 7 days after 10/29. 例如,即使11/1不是在10/29之后的7天, 我的图形也会在10 / 1、10 / 8、10 / 15、10 / 22、10 / 29和11/1处显示刻度。 If I expand this range to include multiple months, I see a tick at the first of every month. 如果我将此范围扩展到包括多个月,则每个月的第一天都会出现一个勾号。

I have included my code for this axis below. 我在下面包含了该轴的代码。 What might be causing the first of each month to be displayed as a tick? 是什么导致每月的第一天显示为刻度?

  const xScale = d3.scaleTime().range([0, innerWidth]);
  const tickAmount = d3.timeDay.every(7);

  chart.append("g")
    .classed('x-axis', true)
    .attr("transform", "translate(0," + innerHeight + ")")
    .call(d3.axisBottom(xScale)
    .ticks(tickAmount)
    .tickSize(-innerHeight)
    .tickFormat(d3.timeFormat('%m/%d/%y')));

Try const tickAmount = d3.timeWeek.every(1); 尝试const tickAmount = d3.timeWeek.every(1); instead: 代替:

Note that for some intervals, the resulting dates may not be uniformly-spaced; 请注意,对于某些时间间隔,结果日期可能不会均匀地间隔开; d3.timeDay's parent interval is d3.timeMonth, and thus the interval number resets at the start of each month. d3.timeDay的父间隔是d3.timeMonth,因此间隔号在每个月初重置。 If step is not valid, returns null. 如果step无效,则返回null。 If step is one, returns this interval. 如果step为1,则返回此间隔。 from the d3 docs 来自d3文档

You can also use .tickFormat(function(d, i) { return d; }) to filter out given ticks from display if you like (eg exclude first tick: return i>0 ? d : '' ), though this is more hacky. 如果 .tickFormat(function(d, i) { return d; })您还可以使用 .tickFormat(function(d, i) { return d; })从显示中过滤掉给定的刻度(例如,排除第一个刻度: return i>0 ? d : '' ),尽管这样做更多骇客。

Found a better way to do this from d3 issue tracker : 从d3问题跟踪器中找到了一种更好的方法:

d3.axisBottom(x)
  .ticks(d3.timeDay.filter(d=>d3.timeDay.count(0, d) % N === 0))
  .tickFormat(d3.timeFormat('%m/%d/%y'))
  .tickSizeOuter(0)

This will give you consistent ticks every N-th day without the months repeating. 这将使您在第N天获得一致的滴答声,而无需重复数月。 That a tick exists does not mean a point exists at that date in your dataset, but they are scaled correctly over the date range. 刻度线的存在并不意味着该数据集中在该日期存在一个点,而是可以在日期范围内正确缩放它们。

Here's a demo: https://beta.observablehq.com/@thmsdnnr/d3-ticks-every-7-or-10-days 这是一个演示: https : //beta.observablehq.com/@thmsdnnr/d3-ticks-every-7-or-10-days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM