score:4

Accepted answer

You can get the bounding box of the text and use those values to apply a transform to center it. An example for getting the bounding box is here. The code would look something like

.text(function(d) { return d.Total; })
.attr("x", function(d) {
   return x(d.Year) + (x.rangeBand() / 2) - (this.getBBox().width / 2);
}
...

score:9

A perhaps simpler way is to use a text-anchor of middle with x set to the left side of the bar plus half the width of the bar:

svg.selectAll(".bar-label")
  .data(data)
.enter().append("text")
  .text((d)-> d.Total)
  .attr("class", "bar-label")
  .attr("text-anchor", "middle")
  .attr("x", (d)-> x(d.Year) + x.rangeBand()/2)
  .attr("y", (d)-> y(d.Total) - 5)

Related Query

More Query from same tag