D3.js axis is slightly off

I’m building a bar chart with d3.js, and for some reason my x axis scale is ever so slightly misaligned with my bars. I’ve combed through my code and can’t seem to figure out why. I’m sure it’s something simple, but I just can’t put my finger on it. Any chance I could get another pair of eyes to see what I’ve missed? Here’s a CodePen of the project so far.
Thanks for your help!

I don’t think it is that simple if you are using a continuous scale i.e. d3.scaleTime() for a bar chart . I struggled with such a problem for almost a week without finding a work around. I have noticed with a bar chart, the best scale to use on the x-axis is the d3.scaleBand if you want the calibrations on the axis to align perfectly with the bars.

If you insist on using d3.scaleTime for the x-axis then you will have to forego the spaces between the bars especially with dynamic bar charts like yours (as far as i know). To see what i am talking about, try the following changes to your code.

1.  const barWidth = chartWidth / data.length; // Calculates bar width without gaps between
2.  var xScale = d3.scaleTime(); // Makes the xScale variable accessible in the promise
3.  .attr("x", (d, i) => padding + xScale(d.dateChecked) + barWidth/2)  //Aligns bar with calibration

Thanks for your reply! In case anyone else runs into this problem, I also made a post on StackOverflow which was very helpful and can be found here. The problem was partially using the wrong type of scale, but as you have pointed out, the biggest problem was that I wasn’t calculating bar position based on dates at all, but rather on evenly spacing out the number of bars in the available space.
The working code I settled on:

let barWidth = chartWidth / data.length;
const barSpace = 0.1 * barWidth;
barWidth = barWidth - barSpace;

let rect = svg
        .attr("class", "bar")
        .attr("width", barWidth)
        .attr("height", (d) => yScale(0) - yScale(d.positiveIncrease))
        .attr("x", (d, i) => xScale(d.dateChecked) + padding)
        .attr("y", (d) => yScale(d.positiveIncrease) + padding);
1 Like