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
I ran into this problem when changing zoom levels on a bar chart with a time series based x-axis and found two solutions.
1) Create a companion ordinal scale to help calculate the widths.(a pain)
2) The time-series x axis is your friend - use it to calculate the width.
If you want your bar to always be a "month" wide, irrespective of zoom level in you can do something like this. Im assuming d.date is available in the data.
svg.selectAll(".air_used").attr("width", function(d.date) {
var next = d3.time.month.offset(d.date, 1);
return (x(next)- x(d));
});
This works well because it works for every zoom scale, and you just need to call this function at the end of your on "zoom" handler ie .on("zoom", zoomed); The x axis will usually have been adjusted at this point.