2

Pretty basic code for a horizontal bar chart using Apple's Swift Charts:

private var testData: [(String, Int)] = []

init() {
    for i in (0 ..< 10).reversed() {
        testData.append(
            ("Item\(i)", i + 3)
        )
    }
}

var body: some View {
    Chart(testData, id: \.0) { item in
        BarMark(
            x: .value("x", item.1),
            y: .value("y", item.0)
        )
        .foregroundStyle(Color.red)
        .annotation(
            position: .overlay,
            alignment: .trailing
        ) {
            Text("\(item.1)")
                .foregroundColor(.white)
                .fontWeight(.bold)
                .padding(.trailing)
        }
    }
    .chartXAxis(.hidden)
    .chartYAxis {
        AxisMarks(
            position: .trailing
        ) { value in
            AxisValueLabel(centered: true) {
                if let stringValue = value.as(String.self) {
                    Text(stringValue)
                        .font(.title2)
                }
            }
        }
    }
}

With this result but I can't seem to prevent the chart from overlapping the Y axis label:

enter image description here

Even if I align the label with position: .leading it's still hidden under the chart. Any help would be appreciated.

William T.
  • 12,831
  • 4
  • 56
  • 53
  • 6
    Try this in `.chartYAxis`: `AxisMarks(preset: .extended, position: .trailing, values: testData.map(\.0))`. – Cenk Bilgen Jan 02 '23 at 23:59
  • Whoa, that worked! Looks like all I needed was `preset: .extended` and that solved it. Thanks! if you want to post your comment as an answer, I'll be happy to mark it. – William T. Jan 03 '23 at 01:12

0 Answers0