3

我已经尝试.ticks(d3.time.days, 2)在此设置 xAxis 的配置时间范围。

var data = [{"date":"2012-03-20","total":3},{"date":"2012-03-21","total":8},{"date":"2012-03-22","total":2},{"date":"2012-03-23","total":10},{"date":"2012-03-24","total":3},{"date":"2012-03-25","total":20},{"date":"2012-03-26","total":12}, {"date":"2012-03-27","total":22}, {"date":"2012-03-28","total":21}, {"date":"2012-03-29","total":12}, {"date":"2012-03-30","total":12}, {"date":"2012-03-31","total":12}, {"date":"2012-04-1","total":12}];

var margin = {top: 40, right: 40, bottom: 40, left:40},
    width = 600,
    height = 500;

var x = d3.time.scale()
    .domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
    .rangeRound([0, width - margin.left - margin.right]);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.total; })])
    .range([height - margin.top - margin.bottom, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')
    .ticks(d3.time.days, 2)
    .tickFormat(d3.time.format('%a %d'))
    .tickSize(0)
    .tickPadding(20);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient('left')
    .tickPadding(8);

var svg = d3.select('body').append('svg')
    .attr('class', 'chart')
    .attr('width', width)
    .attr('height', height)
  .append('g')
    .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

svg.selectAll('.chart')
    .data(data)
  .enter().append('rect')
    .attr('class', 'bar')
    .attr('x', function(d) { return x(new Date(d.date)); })
    .attr('y', function(d) { return height - margin.top - margin.bottom - (height - margin.top - margin.bottom - y(d.total)) })
    .attr('width', 10)
    .attr('height', function(d) { return height - margin.top - margin.bottom - y(d.total) });

svg.append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0, ' + (height - margin.top - margin.bottom) + ')')
    .call(xAxis);

    svg.append('g')
      .attr('class', 'y axis')
      .call(yAxis);

但是时间范围是 Sat 31 - Sun 1。我希望它是 Sat 31 - Mon 2。

这是一个jsFiddle

4

1 回答 1

5

我更新了你的小提琴,相关部分如下:

var startDate = new Date(data[0].date);
var endDate = new Date(data[data.length - 1].date);

var everyOtherIncorrect = d3.time.day.range(startDate, endDate, 2);

var everyDate = d3.time.day.range(startDate, endDate);
var everyOtherCorrect = everyDate.filter(function (d, i) {
    return i % 2 == 0;
});

您的问题是它d3.time.day.range(start, end, 2)实际上并不是每隔一天生成一次,而是总是从每月 1 日开始。(参见 D3 API 参考

使用时也会出现同样的问题

d3.svg.axis().ticks(d3.time.days, 2)

因此,如果您将其替换为手动生成的日期,它将产生所需的结果:

d3.svg.axis().tickValues(everyOtherCorrect)
于 2013-04-24T08:10:23.797 回答