liveBook · Manning

SVG text

As explained in D3.js in Action, Third Edition

SVG text is textual content represented by a <text> element positioned within an SVG graphic.

SVG text places readable characters inside a graphic with a <text> opening tag and closing tag. Unlike most SVG shapes, its content sits between those tags. Position it with x and y in the SVG coordinate system; if it is missing, inspect the DOM and check whether it lies outside the viewBox. section 1.2.2

The x position sets the horizontal reference point, while y positions the text baseline. Horizontal alignment defaults to start; use text-anchor="middle" or "end" when a label must align around or before its coordinate. Control vertical alignment with dominant-baseline: middle centers on the baseline coordinate, and hanging shifts text toward its top. section 1.2.2 section 4.3.2

For chart labels, bind each text element to the same data and group as its mark:

  • Append text to each bar group, set its content with .text(d => d.technology), then place category names just left of the bars with x, y, and text-anchor="end". section 3.5
  • Place a value label after each bar by deriving x from the scaled value plus padding, while using a shared y position within the translated group. section 3.5
  • Style labels with fill or CSS font properties, and use a shared group style when several labels need the same appearance. section 1.2.2

Center a percentage in a donut arc

Create a group for each arc, append its path and text, calculate the arc percentage, and position the text at the arc generator’s centroid. Set text-anchor and dominant-baseline to middle so the percentage centers on that point. section 5.1.4

Listing 5.5 Adding labels on the centroids (donut-charts.js)
const arcs = donutContainer
  .selectAll(`.arc-${year}`)
  .data(annotatedData)
  .join("g")  #1
    .attr("class", `arc-${year}`);

arcs                                                #2
  .append("path")                                 
    .attr("d", arcGenerator)                       
    .attr("fill", d => colorScale(d.data.format)); 

arcs
  .append("text")  #3
    .text(d => {
      d["percentage"] = (d.endAngle - d.startAngle)                   #4
        / (2 * Math.PI);                                             
      return d3.format(".0%")(d.percentage);                         
    })
    .attr("x", d => {               #5
      d["centroid"] = arcGenerator 
        .startAngle(d.startAngle)  
        .endAngle(d.endAngle)      
        .centroid();               
      return d.centroid[0];        
    })                             
    .attr("y", d => d.centroid[1]) 
    .attr("text-anchor", "middle")
    .attr("dominant-baseline", "middle")
    .attr("fill", "#f6fafc")
    .attr("fill-opacity", d => d.percentage  #6
      < 0.05 ? 0 : 1)                       
    .style("font-size", "16px")
    .style("font-weight", 500);

This complete D3 pattern binds arc data to groups, draws each arc, computes its percentage and centroid, and appends a centered SVG text label. section 5.1.4

Text can also become part of an interactive tooltip. Put a background rectangle and text in one group, initially hide the group with opacity, then update the text and translate the group when a pointer enters a chart mark. section 7.3.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains text syntax, coordinate placement, anchors, styling, grouped data binding, centroids, and event-driven updates.
Examples
Demonstrates shape-gallery labels, technology bar labels, temperature annotations, donut percentages, and a temperature tooltip.
What it assumes
Builds from SVG coordinates and elements before applying data-bound text within D3 groups.
What you can do after
Apply it via D3 to append, place, align, style, and update chart labels and tooltip text.
How it connects
Connects text elements to SVG groups, viewBox, scales, arc generators, data binding, tooltips, and mouse events.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.