Reduce Swift Charts Data Without Connecting The Gaps

A sensor chart has two awkward habits when we try to simplify it. Keep every tenth reading and the interesting spike might disappear. Remove missing readings and the line might sail straight through an outage.

The second version is especially flattering to the sensor. Its attendance record has improved without anyone repairing it.

We can reduce the points sent to Swift Charts while keeping a more useful contract: preserve the first, minimum, maximum and last reading in each time bucket, keep disconnected runs separate, and inspect values from the original recording. The reduced line remains a visual approximation. It must not become the input to our statistics.

The three Swift blocks below belong in one file in an iOS app target. This example uses Swift 6.4 and the collection-based LinePlot and PointPlot APIs available from iOS 18. These are established APIs, not an iOS 27 addition. Our function-plot article covers calculated curves; this one deals with measured data. The downloadable Xcode project includes the complete screen, an original-readings list and the checks discussed below.

Start with the question the chart should answer

For a sensor history, we might want to see the range of observed values and when recording stopped. An hourly average answers a different question. Both are useful; the label and reduction need to agree.

Marius Constantinescu’s Swift Charts walkthrough combines weather aggregation with selection. We’ll extend that separation by preserving extrema at their original timestamps, retaining outages, and selecting from unreduced measurements. The first/minimum/maximum/last strategy comes from the established M4 work by Jugel and colleagues. Our fixed-minute buckets do not establish that paper’s pixel-equivalence assumptions, so this is not a lossless rendering claim.

There is real demand for better chart behavior. The Stack Overflow question Improving Swift Charts performance still has no answers as of October 22, 2026. Its three charts update at 120 Hz, though; reducing their data alone would not establish a fix for the update loop. Here we’re tackling the narrower problem of preparing a faithful-enough overview of a completed recording.

Split missing intervals before reducing anything

Our recording uses nonnegative, strictly increasing integer minute offsets. nil, NaN and infinity represent unusable measurements and break the line. A larger-than-allowed interval between finite readings also starts a new run. Choose that maximum gap from the sensor’s sampling contract; it isn’t a chart styling preference.

First we split the data. Then we reduce each run independently:

import Foundation

nonisolated struct Reading: Equatable, Sendable {
    let minute: Int
    let value: Double?
}

nonisolated struct ChartSample: Equatable, Sendable {
    let minute: Int
    let value: Double
    let run: Int
}

nonisolated enum RecordingError: Error {
    case invalidOrder, invalidInterval
}

nonisolated func splitRuns(
    _ readings: [Reading], maximumGap: Int
) throws -> [[ChartSample]] {
    guard maximumGap > 0 else { throw RecordingError.invalidInterval }
    var runs: [[ChartSample]] = []
    var current: [ChartSample] = []
    var previousMinute: Int?

    for reading in readings {
        guard reading.minute >= 0,
              previousMinute.map({ reading.minute > $0 }) ?? true else {
            throw RecordingError.invalidOrder
        }
        previousMinute = reading.minute

        guard let value = reading.value, value.isFinite else {
            if !current.isEmpty {
                runs.append(current)
                current = []
            }
            continue
        }
        if let last = current.last,
           reading.minute - last.minute > maximumGap {
            runs.append(current)
            current = []
        }
        current.append(ChartSample(
            minute: reading.minute, value: value, run: runs.count
        ))
    }
    if !current.isEmpty { runs.append(current) }
    return runs
}

// Call with one ordered run produced by splitRuns.
nonisolated func reduceRun(
    _ run: [ChartSample], bucketMinutes: Int
) throws -> [ChartSample] {
    guard bucketMinutes > 0 else { throw RecordingError.invalidInterval }
    var output: [ChartSample] = []
    var start = 0

    while start < run.count {
        let bucket = run[start].minute / bucketMinutes
        var end = start + 1
        while end < run.count,
              run[end].minute / bucketMinutes == bucket {
            end += 1
        }
        var minimum = start
        var maximum = start
        for index in start..<end {
            if run[index].value < run[minimum].value { minimum = index }
            if run[index].value > run[maximum].value { maximum = index }
        }
        let indices = Set([start, minimum, maximum, end - 1]).sorted()
        output.append(contentsOf: indices.map { run[$0] })
        start = end
    }
    return output
}

nonisolated struct ChartProjection: Sendable {
    let originals: [Reading]
    let runs: [[ChartSample]]
    let lines: [ChartSample]
    let dots: [ChartSample]

    init(_ readings: [Reading], maximumGap: Int, bucketMinutes: Int) throws {
        guard bucketMinutes > 0 else { throw RecordingError.invalidInterval }
        let runs = try splitRuns(readings, maximumGap: maximumGap)
        let reduced = try runs.map { try reduceRun($0, bucketMinutes: bucketMinutes) }
        originals = readings
        self.runs = runs
        lines = reduced.filter { $0.count > 1 }.flatMap { $0 }
        dots = reduced.filter { $0.count == 1 }.flatMap { $0 }
    }
}

The order of those operations matters. Filtering out nil first would discard the evidence that the line should stop.

Each bucket is an elapsed-time interval anchored at minute zero: with a width of ten, minutes 0–9 share a bucket, followed by 10–19. It is not “every ten elements,” which would give irregular recordings inconsistent time windows.

Within a bucket, we keep original samples and sort their indices before appending them. A peak followed by a trough stays in that order. A flat bucket can contribute fewer than four points because endpoints and extrema may be the same sample. Tied extrema keep their earliest occurrence.

There is deliberately no global four-points-per-bucket promise. Two runs in the same bucket remain two runs. An outage-filled recording can retain many isolated points, which we draw as dots instead of invisible one-point lines.

Inspect the original recording

A reduced line is a poor lookup table. A perfectly ordinary measurement may have been omitted precisely because it wasn’t an endpoint or an extreme.

Swift Charts’ selection API gives us an axis value. We map that value to an original sample, with an explicit tolerance and an earlier-sample tie break:

// Choose within an original run, never across a missing interval.
nonisolated func nearestOriginal(
    in runs: [[ChartSample]], minute: Int, tolerance: Int
) -> ChartSample? {
    guard minute >= 0, tolerance >= 0,
          let run = runs.first(where: {
              guard let first = $0.first, let last = $0.last else { return false }
              return (first.minute...last.minute).contains(minute)
          }) else { return nil }

    var low = 0
    var high = run.count
    while low < high {
        let middle = low + (high - low) / 2
        if run[middle].minute < minute { low = middle + 1 }
        else { high = middle }
    }
    var candidates: [ChartSample] = []
    if low < run.count { candidates.append(run[low]) }
    if low > 0 { candidates.append(run[low - 1]) }
    func distance(_ sample: ChartSample) -> Int {
        sample.minute >= minute ? sample.minute - minute : minute - sample.minute
    }
    let nearest = candidates.min {
        let left = distance($0), right = distance($1)
        return left == right ? $0.minute < $1.minute : left < right
    }
    guard let nearest, distance(nearest) <= tolerance else { return nil }
    return nearest
}

We first require the selected minute to fall inside an original run’s extent. Even an enormous tolerance cannot jump from the middle of an outage to a nearby endpoint. Within a run, binary search finds the two possible neighbors. The function scans the run boundaries, so its cost is linear in the number of runs plus logarithmic in the selected run’s length.

This app uses a one-minute tolerance. A denser or differently sampled recording needs its own tolerance and time representation. Integer minute selection intentionally cannot distinguish sub-minute observations.

Draw runs as separate series

The collection initializer for LinePlot accepts key paths, including a series key. Passing the run identity is what keeps the orange line from joining across missing intervals. PointPlot handles isolated readings.

The small demonstration recording fits in minutes 0–20 and values -10–60. Those domains are explicit below; replace them with suitable domains for your own bounded recording, including sensible empty and constant-value cases.

import SwiftUI
import Charts

@MainActor
struct SensorChart: View {
    let projection: ChartProjection
    let openOriginals: () -> Void
    @State private var gestureMinute: Int?
    @State private var inspectedMinute: Int?

    private var selected: ChartSample? {
        guard let inspectedMinute else { return nil }
        return nearestOriginal(in: projection.runs, minute: inspectedMinute, tolerance: 1)
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("Sensor history").font(.title2)
            Text("\(projection.lines.count + projection.dots.count) displayed points. Blank intervals have no readings.")
            Chart {
                LinePlot(projection.lines,
                    x: .value("Minute", \.minute),
                    y: .value("Reading", \.value),
                    series: .value("Run", \.run))
                    .interpolationMethod(.linear)
                    .foregroundStyle(.orange)
                PointPlot(projection.dots,
                    x: .value("Minute", \.minute),
                    y: .value("Reading", \.value))
                    .foregroundStyle(.orange)
                if let selected {
                    RuleMark(x: .value("Selected minute", selected.minute))
                        .foregroundStyle(.secondary)
                    PointMark(x: .value("Minute", selected.minute),
                              y: .value("Reading", selected.value))
                        .foregroundStyle(.blue)
                }
            }
            // Domains for this small demonstration recording.
            .chartXScale(domain: 0...20)
            .chartYScale(domain: -10...60)
            .chartXAxisLabel("Minutes from start")
            .chartYAxisLabel("Sensor units")
            .chartXSelection(value: $gestureMinute)
            .frame(height: 260)
            .accessibilityLabel("Reduced sensor history")
            .onChange(of: gestureMinute) { _, minute in
                if let minute { inspectedMinute = minute }
            }

            Text(readout)
                .accessibilityIdentifier("reading-detail")
            Button("Show original readings", action: openOriginals)
                .buttonStyle(.bordered)
        }
    }

    private var readout: String {
        if let selected {
            return "Original: minute \(selected.minute), \(selected.value.formatted()) units."
        }
        if let inspectedMinute {
            return "No original reading near minute \(inspectedMinute)."
        }
        return "Touch the chart to inspect an original reading."
    }
}

The last inspected minute stays visible after the gesture ends. The blue marker is an original measurement, so it can sit away from the approximated orange line. That’s useful information, not a drawing error. Touching a gap clears the marker and reports that no nearby original reading exists.

Build ChartProjection once when accepting the recording, rather than rebuilding it on every selection change. Apple’s vectorized-plot session explains the collection-oriented API; reducing the array and avoiding unnecessary recomputation remain separate application decisions. This sample displays an immutable recording. When replacing it, give the screen a new recording identity so its inspection state and original-data page start fresh.

The download wires openOriginals to a paged list of every input row, including a “No reading” label for missing or nonfinite values. Minutes absent from the input have no row. This gives people a way to inspect measurements that the chart omitted without requiring a precise gesture.

That list also matters for accessibility. The chart’s built-in accessibility represents its displayed data; it does not magically regain samples we removed. Pasquale Vittoriosi and Matteo Altobello’s chart accessibility article is a useful guide to chart descriptions and audio graphs. We retain the native chart behavior and clearly label it as reduced, with original values available separately. Automated list checks are not a substitute for testing VoiceOver and audio-graph navigation with people who use them.

Keep a counterexample beside the happy path

The tests use a 10,000-reading fixture that reduces to 396 displayed points. They check every bucket’s original endpoints and extrema, ordering, missing values, elapsed gaps, isolated points and invalid input. A second oracle checks several bucket widths with regular two-minute samples and explicit missing readings.

The more revealing test is a narrow spike: 100 consecutive readings, all zero except a value of 100 at minute 50. A single coarse bucket retains the peak, but the reduced line connects it to distant endpoints. The piecewise-linear area changes from 100 to 4,950 unit-minutes. The peak is correct; its apparent duration is not.

Never calculate averages, area, duration above a threshold or alerts from this projection. Use the original observations with the appropriate sampling rules. Choose a finer display bucket when short-lived shapes matter, or keep the unreduced data when the chart is already small enough. If the task needs exact spike duration, this overview is the wrong representation.

A separate fixture contains 10,000 readings, alternating valid and missing values. Preserving those disconnected runs retains 5,000 points even in one bucket. We still hold the original array and the original runs, too. Fewer drawing points do not imply a fixed memory budget or a measured frame-rate improvement.

For an actual performance change, compare against the unreduced vectorized chart on representative hardware, including preprocessing and update frequency. WWDC26’s profile, fix and verify workflow is the right next step when the app is slow. This article establishes the projection’s behavior, not a universal speedup.

What was checked

The exact examples were compiled with Xcode 27.1 and Swift 6.4 targeting iOS 18, both with ordinary isolation and with default MainActor isolation. The model checks ran on macOS and in an iOS 27 Simulator app. Native interaction tests exercised an omitted original value, a missing interval, the isolated point and the original-data list. The list was also checked at a large accessibility text size.

The project includes those tests and reproduction instructions. Physical-device performance, older iOS runtime behavior and actual VoiceOver/audio-graph use were not verified. The useful guarantee is narrower: the display keeps selected original extrema and separate runs, while inspection keeps access to the source measurements.