我有一个水平时间线,我在 D3.js 中绘制随时间变化的事件:
现在,我想“填充”事件之间的间隙,因此计算每个条形的宽度(类似于甘特图)。这就是我想要实现的目标:
我的逻辑是让 i+1 的位置减去位置,如下所示:
.attr('width', function(d,i){
barWidth = xScale(barData2[i+1].eventTime) - xScale(barData2[i].eventTime);
return barWidth;
})
(其中 barWidth 是空变量,barData2 是数据)
这完成了工作,但也破坏了代码,因为它不会继续代码的其余部分:
我尝试过以各种方式计算这一点,但没有成功。有什么建议么?
var barData2 = [{
eventTime: new Date("Mon May 11 2020 18:25:43 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Mon May 11 2020 18:34:14 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Mon May 11 2020 22:10:42 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Mon May 11 2020 22:14:46 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Mon May 11 2020 22:22:25 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Mon May 11 2020 22:30:35 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Tue May 12 2020 00:40:00 GMT+0100 (British Summer Time)")
}, {
eventTime: new Date("Tue May 12 2020 05:00:57 GMT+0100 (British Summer Time)")
}];
var barWidth = 0;
var height = 200,
width = 900,
barHeight = 10;
var xScale = d3.time.scale()
.domain([barData2[0].eventTime, barData2[(barData2.length - 1)].eventTime])
.range([0, width - 85]);
var xScale2 = d3.time.scale()
.domain([barData2[0].eventTime, barData2[(barData2.length - 1)].eventTime])
.range([0, width - 85]);
var xAxisTicks = d3.axisBottom(xScale)
.ticks(d3.timeHour.every(1));
var toolTip = d3.select('body')
.append('div')
.style('position', 'absolute')
.style('padding', '0 10px')
.style('background', 'white')
.style('opacity', 0);
d3.select('#viz').append('svg')
.attr('width', width)
.attr('height', height)
.style('background', '#aaa')
.append('g')
.selectAll('rect').data(barData2)
.enter().append('rect')
.attr('y', function(d, i) {
return i * barHeight;
})
四季花海
相关分类