Adding .chartScrollableAxes(.horizontal) to a chart prevents chartYAxisLabel from being positioned top right, over Y axis.
We want the label at top right, over the Y-axis, but with chartScrollableAxes it is always top right relative to the initial chartXVisibleDomain, which puts it in the middle of the chart if chartXVisibleDomain < full x domain.
import SwiftUI
import Charts
struct ContentView: View {
@State private var numbers = (0..<100)
.map { _ in Double.random(in: 0...100) }
@State var visibleDomain : Int = 50
var body: some View {
Chart(Array(zip(numbers.indices, numbers)), id: \.1) { index, number in
LineMark(
x: .value("Index", index),
y: .value("Number", number)
)
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: visibleDomain)
.chartScrollPosition(initialX: 70)
.chartYAxisLabel(position: .topTrailing, alignment: .center) {
/*
We want the label at top right, over the Y-axis, but with
chartScrollableAxes it is always top right relative to the initial
chartXVisibleDomain, which puts it in the middle of the chart if
chartXVisibleDomain < full x domain
*/
Text("units")
.foregroundStyle(.red)
.fontWeight(.bold)
}
.padding()
}
}
#Preview {
ContentView()
}