skip to content

In Swift Charts, how do you draw a 10,000-step goal line across a weekly bar chart and stop the y-axis rescaling every week?

level: middleimportance: should knowfreq 40%

answer

  1. a mark for a constant
  2. outside the per-element closure
  3. annotation labels a mark
  4. chartYScale with a domain
  5. ClosedRange, not Range

basics

~10 s

Add one RuleMark(y: .value("Goal", 10_000)) beside a ForEach of BarMarks inside Chart { }, label it with annotation, and fix the axis with chartYScale(domain: 0...15_000) so it stops following each week's data.

solid answer

~40 s

A goal is a constant, so it is one `RuleMark(y: .value("Goal", goal))`. With no `xStart` or `xEnd` it spans the whole plot horizontally. Put it in the builder form, `Chart { ForEach(week) { BarMark(...) }; RuleMark(...) }`: inside `Chart(week) { entry in ... }` the closure runs once per element, so you would draw seven identical rules on top of each other. Style it with `foregroundStyle` and `lineStyle(StrokeStyle(...))`, and label it with `.annotation(position: .top)`. By default the y domain comes from the data, so a quiet week shrinks the axis. `.chartYScale(domain: 0...15_000)` fixes it; the domain is a `ClosedRange` or an array, and a half-open `0..<15_000` does not compile because `Range` does not conform to `ScaleDomain`. Choose an upper bound that covers both the goal and the largest realistic day.

code

swift · 32 lines
swift
import SwiftUI
import Charts

struct DailySteps: Identifiable {
    let id = UUID()
    let day: Date
    let steps: Int
}

struct GoalStepsChart: View {
    let week: [DailySteps]
    let goal = 10_000

    var body: some View {
        Chart {
            ForEach(week) { entry in
                BarMark(
                    x: .value("Day", entry.day, unit: .day),
                    y: .value("Steps", entry.steps)
                )
            }
            RuleMark(y: .value("Goal", goal))
                .foregroundStyle(.red)
                .lineStyle(StrokeStyle(lineWidth: 2, dash: [5, 4]))
                .annotation(position: .top, alignment: .leading) {
                    Text("Goal \(goal)")
                        .font(.caption)
                }
        }
        .chartYScale(domain: 0...15_000)
    }
}

go deeper

for a junior

Recall that a constant line is a RuleMark with only y: given, and that chartYScale(domain:) fixes the axis range.

for a middle

Explain why the rule belongs outside the per-element closure, which domain types compile, and how annotation attaches a label to a mark.

for a senior

Choose a domain that survives record days, keep axis marks consistent with it, and spot duplicated constant marks in review before accessibility testing does.

for a principal

Decide whether fixed or inferred domains are the team default for comparable screens, and where the bounds are computed so every chart agrees.

## `RuleMark`: a mark for a constant `RuleMark` draws a straight horizontal or vertical line. Apple's documentation says rule marks let "viewers easily compare values over a range to a constant value", which is exactly what a step goal needs. The initializers decide its direction: | Initializer | Draws | |---|---| | `RuleMark(y:)` | a horizontal line at that y, across the plot | | `RuleMark(x:)` | a vertical line at that x, top to bottom | | `RuleMark(xStart:xEnd:y:)` | a horizontal segment between two x values | | `RuleMark(x:yStart:yEnd:)` | a vertical segment between two y values, as in a range chart | When you omit the optional start and end parameters, the rule spans the plotting area. So `RuleMark(y: .value("Goal", 10_000))` is the whole goal line. ## Where the `RuleMark` goes The data initializer `Chart(week) { entry in ... }` is built on `ForEach`: the closure runs once per element. A `RuleMark` written inside it is emitted once per element too, and because its y never changes, seven rules land on exactly the same pixels. It looks right, so the defect hides until the line is translucent and looks heavier than designed, or someone counts the chart's marks. The fix is the builder form, where you own the loop: ```swift Chart { ForEach(week) { entry in BarMark(x: .value("Day", entry.day, unit: .day), y: .value("Steps", entry.steps)) } RuleMark(y: .value("Goal", goal)) } ``` ## Labelling the line Chart content has an `annotation(position:alignment:spacing:content:)` modifier that attaches a SwiftUI view to a mark. On the rule, `.annotation(position: .top, alignment: .leading) { Text("Goal 10,000") }` puts a caption just above the line at its leading end. Give the line its own look with: - `foregroundStyle(.red)` or any `ShapeStyle`; - `lineStyle(StrokeStyle(lineWidth: 2, dash: [5, 4]))` for a dashed rule; - `accessibilityLabel(_:)` if "Goal" alone would read poorly with VoiceOver. ## Fixing the y-axis with `chartYScale(domain:)` Unless you say otherwise, Swift Charts infers each axis's **domain**, the range of data values it shows, from the marks. That is usually right, but for a weekly screen it means the axis top moves every week and two weeks cannot be compared at a glance. Apple's axis article shows the remedy for a battery chart, `.chartYScale(domain: [0, 100])`: fix the domain to the range that makes sense for the quantity. The `domain:` parameter is generic over `ScaleDomain`, and only a few types conform: | Argument | Result | |---|---| | `0...15_000` (`ClosedRange`) | compiles; fixed numeric domain | | `[0, 15_000]` (`Array`) | compiles; fixed domain from the values | | `.automatic(includesZero: true)` | keeps inference with adjustments | | `0..<15_000` (`Range`) | error: requires that 'Range<Int>' conform to 'ScaleDomain' | A fixed domain no longer grows with the data, so you own the upper bound. Compute it, for example as the larger of the goal and the week's maximum rounded up, if records are possible. ## Axis marks to match With a fixed domain you usually want predictable gridlines as well. `chartYAxis { AxisMarks(values: [0, 5_000, 10_000, 15_000]) }` places marks at those values, and `chartYAxisLabel("Steps")` titles the axis. Note that `AxisMarks` only chooses where ticks, gridlines and labels go; it does not change the domain. ## Rules that span a range The same mark covers more than goal lines. Two other initializers draw segments instead of full-width lines: - `RuleMark(xStart:xEnd:y:)` draws a horizontal segment between two x values, for example a goal that only applied from Wednesday onwards; - `RuleMark(x:yStart:yEnd:)` draws a vertical segment at one x between two y values, which is how a heart-rate screen shows each day's minimum-to-maximum range. A range chart is just a `ForEach` of the second form, often combined with a `PointMark` at each day's average. For a filled band rather than a line, such as a recommended zone, `RectangleMark` takes the same start and end parameters. ## Common mistakes 1. Writing the `RuleMark` inside the per-element closure. 2. Passing a half-open range to `chartYScale(domain:)`. 3. Trying to fix the range with `AxisMarks(values:)`, which changes the labels but not the scale. 4. Hard-coding a domain smaller than real data can reach. 5. Using `RuleMark(x:)` for a goal and getting a vertical line.

  • In Swift Charts, how do you show a target band, say 8,000 to 12,000 steps, instead of a single line?
    Use a `RectangleMark(yStart: .value("Low", 8_000), yEnd: .value("High", 12_000))`, leaving its optional `xStart` and `xEnd` at `nil` so the band covers the plot's width, and give it a translucent `foregroundStyle`. Keep the style translucent so the bars stay readable through the band.
  • In Swift Charts, how do you keep automatic scaling but make sure zero is included?
    Pass `.automatic(includesZero: true)` as the domain: `.chartYScale(domain: .automatic(includesZero: true))`. Charts still infers the upper bound from the data, while you settle the lower bound. The same `automatic` form also takes `reversed:` to flip the axis.

  • A RuleMark inside Chart(data) is drawn once, since its value never changes
  • chartYScale(domain: 0..<15_000) is a valid way to fix the axis
  • AxisMarks(values:) sets the range the y-axis covers
  • A goal line needs its own ForEach to be drawn
  • RuleMark(x:) draws a horizontal goal line