在 x 轴上仅显示特定标签

Show only specific labels on x-axis

我正在尝试 select 仅在我的 X 轴上显示特定范围的标签。基本上它是一个时间序列,我想每隔一个月 select 显示在轴标签中。但是想不出办法。

这是我的fiddle到目前为止

http://jsfiddle.net/sourabhtewari/1n19kwpv/

我的代码目前看起来像这样

var stuff = [{
    "year": 2015,
    "month": 12,
    "s1": 0.38
  },
  {
    "year": 2016,
    "month": 1,
    "s1": 0.39
  },
  {
    "year": 2016,
    "month": 2,
    "s1": 0.43
  },
  {
    "year": 2016,
    "month": 3,
    "s1": 0.40
  },
  {
    "year": 2016,
    "month": 4,
    "s1": 0.39
  },
  {
    "year": 2016,
    "month": 5,
    "s1": 0.39
  },
  {
    "year": 2016,
    "month": 6,
    "s1": 0.38
  },
  {
    "year": 2016,
    "month": 7,
    "s1": 0.37
  },
  {
    "year": 2016,
    "month": 8,
    "s1": 0.37
  },
  {
    "year": 2016,
    "month": 9,
    "s1": 0.35
  },
  {
    "year": 2016,
    "month": 10,
    "s1": 0.37
  },
  {
    "year": 2016,
    "month": 11,
    "s1": 0.36
  },
  {
    "year": 2016,
    "month": 12,
    "s1": 0.37
  },
  {
    "year": 2017,
    "month": 1,
    "s1": 0.35
  },
  {
    "year": 2017,
    "month": 2,
    "s1": 0.36
  },
  {
    "year": 2017,
    "month": 3,
    "s1": 0.37
  },
  {
    "year": 2017,
    "month": 4,
    "s1": 0.38
  },
  {
    "year": 2017,
    "month": 5,
    "s1": 0.35
  },
  {
    "year": 2017,
    "month": 0.36,
    "s1": 0.36
  },
  {
    "year": 2017,
    "month": 7,
    "s1": 0.36
  },
  {
    "year": 2017,
    "month": 8,
    "s1": 0.35
  },
  {
    "year": 2017,
    "month": 9,
    "s1": 0.36
  },
  {
    "year": 2017,
    "month": 10,
    "s1": 0.37
  },



];

var vals = [];
for (var i = 0; i < stuff.length; ++i) {
  var date = new Date(stuff[i]["year"], stuff[i]["month"] - 1, 1);
  vals.push({
    x: date,
    y: stuff[i]["s1"]
  });

}

nv.addGraph(function() {
  var data = [{
    "values": vals,
    "key": "s1",
    "color": "#000000"
  }];
  var chart = nv.models.lineChart()
    .forceY([0, 0.5]);

  chart.xAxis.axisLabel("Date (m/y)")
    .tickFormat(function(d, i) {
      if (i % 2 == 1) d3.select(this).remove();
      console.log(i);
      return d3.time.format("%b-%y")(new Date(d))
    });


  chart.yAxis.axisLabel("s1").tickFormat(d3.format(","));

  d3.select("#chart svg")
    .datum(data)
    .call(chart);

  nv.utils.windowResize(function() {
    d3.select("#chart svg").call(chart)
  });

  return chart;
});

尝试为 xAxis 添加刻度(d3.utcMonth)。

chart.xAxis.axisLabel("Date (m/y)")
  .ticks(d3.utcMonth)
  .tickFormat(function(d,i) {
    return d3.time.format("%b-%y")(new Date(d))
  }) ;

已更新 fiddle:http://jsfiddle.net/1n19kwpv/10/

我相信这个答案是肯定的,你可以,但有一个可能的警告(如下)。

根据 this,您可以这样做:

// Add the X Axis
svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x)
        .ticks(d3.timeMonth.every(2)));

我不确定的一件事是 d3v3 中是否包含 timeMonth 方法。 nvd3好像还不支持d3v4,这个例子是d3v4做的

希望对您有所帮助。