如何使用 d3.scaleTime 每 6 个月渲染/格式化坐标轴?

How to render/ format axes each 6 month with d3.scaleTime?

我正在尝试使用 d3.js v.4 制作类似 this 的图表。但是我拥有的数据每年两次,与给定的示例不同。如何每 6 个月渲染一次坐标轴?我的数据是每年的二月和八月(2008-2015)。

用 scaleTime 和 startDate 和 endDate 设置你的 x 线 当你创建一个轴时,你可以传递一个 interval with filter to tick func。 如果需要,您还可以使用 tickFormat.

格式化轴刻度

这里是使用 coffeescript 的例子

timeParse= d3.timeParse('%m-%Y');
startDate= timeParse('02-2008');
endDate= timeParse('08-2015');
x= d3.scaleTime()
  .domain d3.extent d3.timeMonth.range startDate, endDate, 6
  .range [0, 700];
xAxis= d3.axisBottom(x)
  .ticks d3.timeMonth.filter (xDate)->
    # january is 00
    # console.log 'getMonth: ', xDate.getMonth();
    if xDate.getMonth() is 1 or xDate.getMonth() is 7
      true;
    else
      false;
  .tickFormat d3.timeFormat '%b %Y';

svg.append 'g'
  .attr 'class', 'axis-group'
  .attr 'transform', "translate(0, 300)"
  .call  xAxis;

输出:

请注意,停止范围被排除在外 here

参考:

  1. Month Axis