I\'m building a D3 bar chart with a time scale on the x-axis. The range of the x-axis can vary.
How can I specify the correct width for the bars on the bar chart? I
There's no function to get the width, but you can calculate it quite easily:
.attr("width", width/data.length);
You might want to subtract a small amount from that if you don't want the bars to touch. You would also need to adjust the x
position accordingly, e.g.
.attr("x", function(d) { return x(d.date) - (width/data.length)/2; })
.attr("width", width/data.length);
To get the ticks to align properly, you'll also need to adjust the range of the x axis scale because the first tick will be placed at the first value:
var x = d3.time.scale().range([width/data.length/2, width-width/data.length/2]);
Complete jsfiddle here.