0

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):

enter image description here

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:

enter image description here

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.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Dan Flict
  • 117
  • 8
  • This problem only appears to be happening when the Y-axis label is a Date object, so I found a workaround: I converted each Date label into a String and the problem went away. It's not an answer to my question, that's why I'm posting it as a comment. – Dan Flict Apr 07 '23 at 11:24

0 Answers0