gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:38:08 25 4
gpt4 key购买 nike

我是 d3 新手,但我已使用 d3.timeDay.every(7) 将 x 轴的刻度间隔设置为每 7 天。然而,当我的图表创建时,我还看到每个月的第一天添加了一个刻度线。例如,my graph显示 10/1、10/8、10/15、10/22、10/29 和 11/1 的刻度,即使 11/1 不是 10/29 后的 7 天。如果我将此范围扩大到包括多个月份,我会在每个月的第一天看到一个勾号。

我在下面包含了该轴的代码。是什么导致每月的第一天显示为勾号?

  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')));

最佳答案

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

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. If step is not valid, returns null. If step is one, returns this interval. from the d3 docs

如果您愿意,您还可以使用 .tickFormat(function(d, i) { return d; }) 从显示中过滤掉给定的刻度(例如排除第一个刻度: return i>0 ? d : ''),尽管这比较hacky。

找到了更好的方法来做到这一点from d3 issue tracker :

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

这将为您提供每 N 天一致的刻度,而不会重复月份。存在刻度并不意味着数据集中在该日期存在点,但它们在日期范围内正确缩放。

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

关于javascript - 即使我将刻度间隔设置为每 7 天,为什么我的 d3 图表的 x 轴仍将每个月的第一天作为刻度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49178363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com