An arc generator turns radii and angles into the `d` attribute of an SVG path. Use `d3.arc()` when a chart needs a circular slice or a ring segment: it saves you from writing path commands by hand. An inner radius of 0 makes a pie slice; a larger inner radius leaves a hole for a donut chart. section 4.0 section 4.4.2
To draw a pair of arcs showing days with and without precipitation:
- Count the days with precipitation, divide by the total, and convert that share of a full circle into radians. The generator expects radians, not degrees. section 4.4.1
- Translate an SVG group to the chart’s center, then configure `d3.arc().innerRadius(80).outerRadius(120)`. Add `padAngle(0.02)` for a gap and `cornerRadius(6)` for rounded ends. section 4.4.1 section 4.4.2
- Append two paths. Give the first angles from 0 to the precipitation angle; give the second angles from there to `2 * Math.PI`. Call the generator for each path’s `d` attribute. section 4.4.2
Draw the precipitation arc
With the percentage already converted to `angleDaysWithPrecipitation_rad`: const arcGenerator = d3.arc() .innerRadius(80) .outerRadius(120) .padAngle(0.02) .cornerRadius(6); innerChart.append("path") .attr("d", arcGenerator({ startAngle: 0, endAngle: angleDaysWithPrecipitation_rad })) .attr("fill", "#6EB7C2"); Angle 0 starts at 12 o’clock. In the precipitation example, this blue arc represents 35% of the days; a gray arc fills the rest of the circle. section 4.4.2
For many slices, `d3.pie()` can supply each slice’s `startAngle` and `endAngle`. Set the generator’s angle accessors to read those values, bind the annotated data to paths, and use `.attr("d", arcGenerator)`. To make an angle easier to read, position a percentage label using the two coordinates returned by `arcGenerator.centroid()`. section 5.1.3 section 5.1.4
Listing 5.4 Generating and drawing the arcs (donut-charts.js)
const arcGenerator = d3.arc()
.startAngle(d => d.startAngle) #1
.endAngle(d => d.endAngle)
.innerRadius(60)
.outerRadius(100)
.padAngle(0.02)
.cornerRadius(3);
const arcs = donutContainer
.selectAll(`.arc-${year}`) #2
.data(annotatedData)
.join("path")
.attr("class", `arc-${year}`)
.attr("d", arcGenerator); #3
See the complete data-bound donut-slice pattern, from angle accessors through the SVG path’s `d` attribute. section 5.1.3
