I am working with datasets whose minimum values are far from zero. When I plot such data with Swift Charts, by default Swift Charts autoscales (using a nice-number algorithm) and gives me something that looks like this:

Since zero is always included, the data doesn’t fill much of the window. I will call this a "loose" autoscale. What I would like is a "tight" autoscale, so the data is plotted more like this:

I can achieve this effect by keeping track of the minimum and maximum in my dataset and then simply add the chart modifier:
.chartYScale(domain: yMin...yMax)
As I add and drop data from my array I need to recalculate the min/max each time. Is there some option in Swift Charts to do this "tight" autoscale automatically? It would simplify parts of my code significantly.
>Solution :
It seems like default behaviour looks "bad" because it includes 0.
You can ask for an automatic Y scale that does not include 0:
.chartYScale(domain: .automatic(includesZero: false))
Minimal reproducible example:
struct Foo: Identifiable {
let x: Int
let y: Int
var id: Int { x }
}
let data = (0..<100).map { Foo(x: $0, y: Int.random(in: 40000..<50000)) }
struct ContentView: View {
var body: some View {
Chart(data) { datum in
LineMark(x: .value("X", datum.x), y: .value("Y", datum.y))
}
// compare the result with and without this line
.chartYScale(domain: .automatic(includesZero: false))
}
}