I'm using the new SwiftUI Charts framework to display data in a vertical bar chart, but I'm having trouble centering the Y-axis date labels on each bar:
struct ChartEntry: Identifiable {
var id = UUID()
let labelDate: Date
let amount: Int
}
struct ContentView: View {
let chartContent: [ChartEntry]
var body: some View {
Chart {
ForEach(chartContent) { entry in
BarMark(x: .value("Value", entry.amount),
y: .value("Hour Label", entry.labelDate, unit: .hour))
}
}
.chartYAxis {
AxisMarks(position: .leading, values: chartContent.map{$0.labelDate}) { data in
AxisValueLabel()
}
}
.chartXScale(domain: 0...50)
}
}
This code generates a chart with Y-axis date labels aligned to the bottom of the bars (I populated the chartContent object with sample entries):
I want to center the labels on each bar.
I've tried AxisValueLabel(centered: true)
. It moved all the Y-axis date labels down in an apparent random amount. Now they are misaligned and in the wrong place. Additionally, the first row is missing a label:
I've also tried AxisMarks(preset: .aligned)
, but it doesn't change anything.
How can I center the Y-axis date labels on each bar?
I'm aware of this question and this question, but these solutions do not solve the problem.
Thank you very much.