liveBook · Manning

Centroid

As explained in D3.js in Action, Third Edition

A centroid is the geometric center of a shape or region.

A centroid is the geometric center, or center of mass, of a shape or region. For an arc, D3 calculates it as a two-value array containing horizontal and vertical coordinates relative to the chart origin. section 4.4.3 section 4.5

Use an arc centroid to place labels accurately:

  • Configure the arc generator with its start and end angles. section 4.4.3
  • Call centroid() to obtain the label position. section 4.5
  • Assign the returned coordinates to an SVG text element and center its text with text-anchor and dominant-baseline. section 4.4.3
const centroid = arcGenerator
  .startAngle(0)
  .endAngle(angleDaysWithPrecipitation_rad)
  .centroid();

This listing shows the compact D3 method chain for calculating an arc centroid from its angular bounds. section 4.4.3

Labeling a donut arc

For an arc representing 35% of days with precipitation, calculate its centroid and use the two returned values as the x and y coordinates of a white percentage label. Apply the same pattern to every donut-chart arc. section 4.4.3 section 5.1.4

How D3.js in Action, Third Edition covers it

How deep it goes
Explains centroid calculation, returned coordinates, and SVG alignment, but defers general shape-centroid mathematics.
Examples
Demonstrates a 35% precipitation label and percentage labels placed on multiple donut-chart arcs.
What it assumes
Assumes an arc generator and radians while teaching centroid calculation and SVG label alignment through examples.
What you can do after
Apply it via D3’s arc generator to calculate and align labels inside pie or donut-chart arcs.
How it connects
Connects arc generators with polar coordinates, SVG text, pie charts, donut charts, and data binding.

Also explained in

Compare how 7 books explain centroid →

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.