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

标签 javascript d3.js linechart axes

我是 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/

相关文章:

javascript - D3 饼图弧线过渡到 180° 时不可见

javascript - D3.js 流图过渡没有绘制任何内容

javascript - 在 JSON 文件中写什么来创建多折线图 HTML

google-visualization - 如何设置工具提示以显示百分比以匹配 Google 可视化折线图中的轴?

c#如何绘制折线图

javascript 选择器 document.object

javascript - Angular BehaviorSubject 不发送下一个

javascript - Dojo has/sniff 和 OS 检测

javascript - 深色背景中的 c3 图;如何更改轴和刻度值颜色

javascript - 大尺寸图片不上传