我已尝试在此设置xAxis的配置时间范围.ticks(d3.time.days, 2)
。
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);
但时间范围是星期六31 - 太阳1.我希望它是星期六31 - 星期一。
这是jsFiddle。
答案 0 :(得分:4)
我更新了your fiddle,相关部分如下:
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)
实际上并不是每隔一天生成一次,而是始终从该月的第一天开始。 (Cf the D3 API reference)
使用
时会出现同样的问题d3.svg.axis().ticks(d3.time.days, 2)
因此,如果您通过手动生成的日期替换它,它将产生所需的结果:
d3.svg.axis().tickValues(everyOtherCorrect)