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:
How can we create axis labels like those in red above – or otherwise add units/descriptions to our axes?
2
Answers
This is the correct modifier:
You can also provide a custom view like this:
One way to create those red labels is to use a combination of Text with VStack or HStack as needed. The text can be rotated using rotationEffect(). This is the original code with modifications:
This is the resulting layout:
Use AxisMarks() to change the default axis marks including labels, grid lines and tick marks. Within AxisMarks individual axis labels can be assigned using AxisValueLabel(). Text() is formatted as an individual label for AxisValueLabel()’s content.
When AxisMarks is used, the default grid lines and tick marks disappear, so they have been added back using AxisGridLine() and AxisTick(). The following code should be added immediately following Chart{} and replacing the original .chartYAxis():
The chart with custom labels will look like this: