Search code examples
swiftuiswiftui-charts

How to label axes in Swift Charts?


I'm trying to add axis unit labels to a chart built with Swift Charts.

For example:

import SwiftUI
import Charts

struct ContentView: View {
    
    struct ChartData: Identifiable {
        var id: Double { xVal }
        let xVal: Double
        let yVal: Double
    }
    
    let data: [ChartData] = [
        .init(xVal: -5, yVal: 5),
        .init(xVal: 0, yVal: 10),
        .init(xVal: 5, yVal: 20),
    ]
    
    var body: some View {
        Chart(data) {
            LineMark(
                x: .value("Position", $0.xVal),
                y: .value("Height", $0.yVal)
            )
        }
        .chartYAxis {
            AxisMarks(position: .leading)
        }
    }
    
}

Chart output, with the desired labels annotated in red: enter image description here

How can we create axis labels like those in red above - or otherwise add units/descriptions to our axes?


Solution

  • This is the correct modifier:

    Chart {
        ...
    }
    .chartXAxisLabel("Position (meters)")
    

    You can also provide a custom view like this:

    
    Chart {
        ...
    }
    .chartXAxisLabel(position: .bottom, alignment: .center) {
        Text("Position (meters)")
    }