How to get the width of the text in the center above the column labels?

I currently have a graph that has associated bar values โ€‹โ€‹displayed above each column, but I am having difficulty centering the value labels due to the inability to extract each width of the text element.

Here's how my chart is being drawn at the moment:

enter image description here

All I have to do is subtract half of each width of the text element, but I cannot do this with the following Coffeescript:

#Drawing value labels svg.selectAll("rect") .data(data) .enter() .append("text") .text((d)-> d.Total) .attr("width", x.rangeBand()) .attr("x", (d)-> textWidth = d3.selectAll("text").attr("width") x(d.Year) + (x.rangeBand() / 2) - (textWidth / 2) ) .attr("y", (d)-> y(d.Total) - 5) .attr("font-size", "10px") .attr("font-family", "sans-serif") #Drawing bars svg.selectAll("rect") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", (d)-> x(d.Year)) .attr("width", x.rangeBand()) .attr("y", (d)-> y(d.Total)) .attr("height", (d)-> height - y(d.Total)) 

Is there a way by which I can access each attribute of the width of a text element to set a value for the offset?

+7
source share
2 answers

You can get the bounding box of the text and use these values โ€‹โ€‹to apply the transformation to center it. An example of obtaining a bounding box is here . The code would look like

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

Perhaps an easier way is to use text-anchor of middle with x set to the left of the panel, plus half the width of the panel:

 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) 
+6
source

All Articles