swiftswiftuiswiftui-charts

How do I change my x labels angle with swiftUI?


I'm a beginner in SwiftUI I would like to change the rotation of my values in the x-axis as shown in this image: Desire chart I currently have it like this in my code:

Chart {
    ForEach(arregloDummy) { arregloDummy in
        LineMark(
            x: .value("Periodo", arregloDummy.periodo.orEmpty),
            y: .value("Consumo", arregloDummy.consumo ?? 0.0))
    }
}
    .frame(height: 200)
    .padding()
    .foregroundColor(Color(cgColor: ColorSet.accentColor.cgColor))
    .background(Color(red: 213 / 255, green: 218 / 255, blue: 198 / 255))
    .chartYAxis{
        AxisMarks(position: .leading)
    }

and this is how it appears: Current chart

I tried to use .rotationEffect, but it rotates my entire chart.


Solution

  • I think you can use .chartXAxis to customize the labels. If the values are Int then it might look something like:

        Chart {
            // Content as before
        }
        .chartXAxis {
            AxisMarks(position: .bottom, values: .automatic) { value in
                AxisValueLabel() {
                    if let intValue = value.as(Int.self) {
                        Text("\(intValue)")
                            .rotationEffect(.degrees(-35))
                    }
                }
            }
        }