skip to content

In Swift Charts on iOS 17 and later, how do you build a spending donut by category with SectorMark, and find which slice the user touched?

level: seniorimportance: nice to knowfreq 30%

answer

  1. angle encodes the amount
  2. a non-zero inner radius
  3. category through foregroundStyle(by:)
  4. a running total along the angle
  5. chartBackground for the centre

basics

~10 s

Plot SectorMark(angle: .value("Amount", amount), innerRadius: .ratio(0.618)) per category with foregroundStyle(by:); chartAngleSelection(value:) returns a value along the running total, which you map back to a category by summing amounts in data order.

solid answer

~40 s

`SectorMark`, added in iOS 17, maps each value to an angular share of the total. `SectorMark(angle: .value("Amount", item.amount), innerRadius: .ratio(0.618), angularInset: 1.5)` makes a donut: a non-zero `innerRadius` is what turns a pie into a donut, and a small `angularInset` separates slices. `.foregroundStyle(by: .value("Category", item.category))` colours each slice and adds a legend. Amounts must be positive. For touch, `chartAngleSelection(value: $raw)` binds an optional of the angle's value type, here `Double`: the chart writes a position along the cumulative total, not a category. Walk the data in plot order, adding amounts until the running total reaches that value, and that item is the selected slice. A label in the hole goes in `chartBackground`, positioned at the centre of `proxy.plotFrame`.

code

swift · 37 lines
swift
import SwiftUI
import Charts

struct CategorySpend: Identifiable {
    let id = UUID()
    let category: String
    let amount: Double
}

struct SpendingDonut: View {
    let spending: [CategorySpend]       // sorted by amount, largest first
    @State private var rawAngleValue: Double?

    private var selectedCategory: String? {
        guard let rawAngleValue else { return nil }
        var runningTotal = 0.0
        for item in spending {
            runningTotal += item.amount
            if rawAngleValue <= runningTotal { return item.category }
        }
        return nil
    }

    var body: some View {
        Chart(spending) { item in
            SectorMark(
                angle: .value("Amount", item.amount),
                innerRadius: .ratio(0.618),
                angularInset: 1.5
            )
            .cornerRadius(4)
            .foregroundStyle(by: .value("Category", item.category))
            .opacity(selectedCategory == nil || selectedCategory == item.category ? 1 : 0.4)
        }
        .chartAngleSelection(value: $rawAngleValue)
    }
}

go deeper

for a junior

Recall that SectorMark plots an amount as an angle, that innerRadius makes a donut, and that it needs iOS 17.

for a middle

Explain the MarkDimension forms for the radii, why the category goes through foregroundStyle(by:), and why values must be positive.

for a senior

Map an angle selection back to a slice with a cumulative walk in plot order, centre a label with chartBackground, and keep slices readable for VoiceOver.

for a principal

Set the minimum iOS version your charts may require, since SectorMark and angle selection need iOS 17 and SectorPlot needs iOS 18, and plan fallbacks below it.

## `SectorMark` anatomy `SectorMark` arrived in **iOS 17**. Apple's documentation describes it as "a sector of a pie or donut chart, which shows how individual categories make up a meaningful total". It has a single initializer: | Parameter | Type | Meaning | |---|---|---| | `angle:` | `PlottableValue` | the amount; the share of the full circle it takes | | `innerRadius:` | `MarkDimension`, default `.automatic` | the hole; non-zero gives a donut | | `outerRadius:` | `MarkDimension`, default `.automatic` | the outer edge, for example `.inset(10)` | | `angularInset:` | `CGFloat?`, default `nil` | a gap between neighbouring sectors | `MarkDimension` has four forms: `.automatic`, `.fixed(_:)` in points, `.ratio(_:)` of the available radius, and `.inset(_:)` from the edge. iOS 18 added `SectorPlot`, the vectorized form for large collections. ## Pie versus donut With the default inner radius you get a pie. The documentation's donut example uses `innerRadius: .ratio(0.618)` and `outerRadius: .inset(10)`, plus `angularInset: 1` and `.cornerRadius(4)`. It also says a small angular inset "helps accessibility and readability by adding contrast between sectors" and advises keeping the inset and corner radius small so slices keep their relative sizes. Two data rules come from the same page: - use positive values only; - very small proportions may be hard to see, especially with an angular inset. ## Colour and legend A sector has no x or y axis, so the category is carried by colour: `.foregroundStyle(by: .value("Category", item.category))`. As with bars and lines, that builds a colour scale and a legend, and `chartForegroundStyleScale` pins specific categories to specific colours. The documentation's pie example supplies data ordered by decreasing value, which also fixes the order the slices are drawn in. ## Selection with `chartAngleSelection` iOS 17's `chartAngleSelection(value:)` takes a `Binding<P?>` with `P` the angle's value type. On a touch, the chart writes a **value on the angle scale**, a point along the running total of all sectors, not the category and not an `Angle`. Resolving it is a cumulative walk: 1. Start a running total at zero. 2. Iterate the data in the same order the chart plots it. 3. Add each amount; the first item whose running total reaches the selected value owns the slice. 4. Return `nil` when the binding is `nil`. With the selected category in hand, emphasise it with chart content modifiers, for example `.opacity(selected == nil || selected == item.category ? 1 : 0.4)` on each sector. If you build a custom gesture through `chartGesture(_:)`, `ChartProxy.angle(at:)` converts a point to an `Angle` and `selectAngleValue(at:)` drives the same binding. ## A label in the hole The centre of a donut is the natural place for "Total: 1,240" or the selected category. `chartBackground` hands you a `ChartProxy`: ```swift .chartBackground { proxy in GeometryReader { geo in if let plotFrame = proxy.plotFrame { let frame = geo[plotFrame] Text("Total").position(x: frame.midX, y: frame.midY) } } } ``` `plotFrame` is an optional anchor available from iOS 17; resolving it in the reader gives the plot's rectangle, whose midpoint is the centre of the sectors. ## Labels on the slices A donut often shows each slice's share on the slice itself. Chart content's `annotation(position:alignment:spacing:content:)` works on sectors as on any mark: `.annotation(position: .overlay) { Text(item.share, format: .percent) }` places the view over the sector. Keep three points in mind: - compute shares yourself from the total, because the angle encoding takes the raw amount, not a fraction; - skip the label for slivers, where the text would not fit; - the documentation's own guidance for many small categories is to sum the remainder into an "Other" group, which also keeps the number of labels manageable. For large collections, iOS 18's `SectorPlot` takes the whole array with key paths, while the angle selection and the centre label are chart-level modifiers that stay the same. ## Accessibility Each sector can carry `accessibilityLabel(_:)` and `accessibilityValue(_:)`, such as the category and a formatted currency amount. The colour-plus-legend encoding is visual only, so give VoiceOver the category name explicitly when the label you passed to `.value` is not enough. ## Common mistakes 1. Treating the selection binding as the category, or as an angle in degrees. 2. Walking the data in a different order from the one plotted. 3. Plotting negative values, such as refunds, as sectors. 4. Making the angular inset so large it distorts the shares. 5. Using `SectorMark` with an iOS 16 deployment target without an availability check.

  • In Swift Charts, how do you turn the spending donut into a plain pie chart?
    Drop the `innerRadius:` argument so it stays at its default, `.automatic`, which gives a pie. Only the hole changes: the angle encoding, `foregroundStyle(by:)`, the legend and the angle selection keep working the same way.

  • chartAngleSelection gives you the category of the touched slice
  • A non-zero angularInset is what makes a donut
  • SectorMark is available from iOS 16 like the other marks
  • Negative amounts plot as slices facing the other way
  • Any data order works when mapping the selection back to a slice

Assumes the iOS 27 SDK; SectorMark, chartAngleSelection and ChartProxy.plotFrame arrived in iOS 17, and SectorPlot in iOS 18.