Calculating width to create continuous horizontal bar in D3.js

The easiest way to get this is by just transforming your data a little bit beforehand. Note that if we have n events, we want to draw n - 1 bars.

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)")
}];

// .slice(1) removes the first entry, because we have n events,
// we want to draw n-1 bars
barData2Processed = barData2.slice(1).map(function(d, i) {
  return {
    // Note that because we removed the first entry, this is
    // actually the previous element, not the current one
    start: barData2[i].eventTime,
    end: d.eventTime
  }
});

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 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(barData2Processed)
  .enter().append('rect')
  .attr('y', function(d, i) {
    return i * barHeight;
  })
  .attr('height', barHeight)
  .attr('width', function(d, i) {
    return xScale(d.end) - xScale(d.start);
  })
  .attr('x', function(d, i) {
    return xScale(d.start);
  })


xGuide = d3.select('#viz svg').append('g')
  .attr('transform', 'translate(0,' + (height - 25) + ')')
  .call(xAxisTicks);
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-time.v2.min.js"></script>
<script src="https://d3js.org/d3-time-format.v3.min.js"></script>

<div id="viz"></div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top