SwiftUI Charts by default take up the entire available width and divides the space between the BarMarks. This code renders the following chart
import SwiftUI
import Charts
struct ContentView: View {
var body: some View {
Chart {
BarMark(x: .value("Item", "A"),
y: .value("Rating", 100),
width: 3.0)
BarMark(x: .value("Item", "B"),
y: .value("Rating", 150),
width: 3.0)
}
.frame(height:200)
}
}
My desired result is this
It's not possible to wrap the BarMarks in a HStack with a Spacer, and I haven't found anything in .chartXAxis{}
that would allow this.
Is it possible to align the BarMarks? So far my only working method is to change the frame width based on the number of BarMarks that are displayed, but that is a very cumbersome method.
As Joakim Danielson pointed out, it's not possible to align the barmarks by default this way. I ended up adding a certain amount of BarMarks with y values of 0. That way they aren't visible, but do take up exactly the amount of space that I want. This is a minimal sample of the code
Chart {
BarMark(x: .value("Item", "A"),
yStart: .value("Rating", 0),
yEnd: .value("Rating", 100))
BarMark(x: .value("Item", "B"),
yStart: .value("Rating", 0),
yEnd: .value("Rating", 150))
BarMark(x: .value("Item", "C"),
yStart: .value("Rating", 0),
yEnd: .value("Rating", 0))
BarMark(x: .value("Item", "D"),
yStart: .value("Rating", 0),
yEnd: .value("Rating", 0))
BarMark(x: .value("Item", "E"),
yStart: .value("Rating", 0),
yEnd: .value("Rating", 0))
}
.chartXAxis {
AxisMarks(position: .bottom) { _ in
AxisValueLabel().foregroundStyle(.clear)
}
}