The SVG text-anchor attribute sets how a text element aligns horizontally around its x position. With end, the x position marks the text’s right edge; with middle, it marks the text’s center. This lets labels meet a chart edge or sit directly over a calculated point. section 3.5 section 4.4.3
For a horizontal bar chart, place technology names just left of bars that begin at x=100. Set each label’s x value to 96, leaving a small gap, then use text-anchor="end" so differently sized names all finish at the same position. Position y separately, remembering that SVG text uses a baseline. section 3.5 section 3.6
barAndLabel
.append("text")
.text(d => d.technology)
.attr("x", 96)
.attr("y", 12)
.attr("text-anchor", "end");
This label code makes x=96 represent the end of every technology name, creating a consistent right-aligned label column beside the bars. section 3.5
Choose an anchor from the label’s intended reference point:
- Use end when text should extend left from its x position, such as labels immediately before horizontal bars. section 3.5 section 8.6.3
- Use middle when text should be centered on its x position, such as a percentage placed at an arc centroid or a year under a grid line. section 4.4.3 section 8.6.3
- Use start when text should extend right from its x position, such as labels placed beyond the right side of a chart. section 8.6.3
Centering a donut-chart label
An arc generator can return a centroid as an [x, y] pair. Apply those coordinates to a text element, then combine text-anchor="middle" with dominant-baseline="middle" to center a formatted percentage both horizontally and vertically on the arc. section 4.4.3
D3 axis labels may already have text-anchor="middle". Their horizontal placement can still be adjusted with x—for example, by calculating the midpoint between the first day of a month and the first day of the next month. Alignment and position work together: text-anchor defines which part of the text meets the coordinate. section 4.1.2
