Course contentsShow
← Web Development
Lesson 2608 of 2,98247. Data VisualizationFree lesson

SVG Text and Labels in Charts

Add accessible text labels, axis labels, and data annotations using <text> and <tspan>.

SVG Text and Labels in Charts

What You'll Learn

You'll learn how to add clear, accessible text labels, axis labels, and data annotations to your SVG charts using the <text> and <tspan> elements.

Why Text Matters in Data Visualization

Charts without labels are like maps without street names—technically they show the data, but users can't interpret what they're seeing. SVG's <text> element lets you place readable, accessible labels exactly where you need them in your visualizations.

The <text> Element

The <text> element positions text at specific coordinates. The x and y attributes define where the text anchor sits:

<text x="50" y="100" fill="black" font-size="14">
  Revenue: $45,000
</text>

Text alignment is controlled by text-anchor:

  • "start" (default) - left-aligned
  • "middle" - centered
  • "end" - right-aligned

For vertical positioning, use dominant-baseline:

  • "hanging" - text hangs below the y position
  • "middle" - vertically centered
  • "baseline" (default) - sits on baseline

Multi-line Text with <tspan>

Since <text> doesn't wrap automatically, use <tspan> for multiple lines:

<text x="100" y="50">
  <tspan x="100" dy="0">Q4 Sales</tspan>
  <tspan x="100" dy="20">2023</tspan>
</text>

The dy attribute shifts each line vertically from the previous one.

Practical Chart Applications

  • Axis labels: Position text near tick marks using calculated coordinates
  • Data labels: Place values above bars or next to data points
  • Legends: Combine text with shapes to explain chart colors
  • Annotations: Call out specific data points with explanatory text

Key Takeaway: Use <text> for single-line labels with text-anchor and dominant-baseline for precise positioning, and <tspan> for multi-line annotations that make your charts readable and accessible.