Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
Hundley Avatar asked Sep 10 '25 21:09

Hundley


1 Answers

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)")
}
like image 179
Hundley Avatar answered Sep 13 '25 15:09

Hundley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!