2

I'm using Swift Charts in a SwiftUI app to make a line chart. I would like to rotate the Y axis label such that it reads from bottom to top. I tried to rotate the text but the rotation causes the label to not render properly. Is there a way to rotate the axis label?

import SwiftUI
import Charts

struct ContentView: View {

    struct Point: Identifiable {
        let id = UUID()
        let x: Float
        let y: Float
    }

    let points = [
        Point(x: 0, y: 1),
        Point(x: 1, y: 4.5),
        Point(x: 2, y: 3),
        Point(x: 3, y: 6),
        Point(x: 4, y: 7),
        Point(x: 5, y: 5.2),
        Point(x: 6, y: 9),
        Point(x: 7, y: 12.5),
    ]

    var body: some View {
        Chart {
            ForEach(points) { point in
                LineMark(
                    x: .value("X values", point.x),
                    y: .value("Y values", point.y)
                )
            }
        }
        .chartXAxisLabel("The x-axis", alignment: .center)
        .chartYAxisLabel(position: .leading) {
            Text("The y-axis")
                .rotationEffect(.degrees(180))
        }
        .chartYAxis {
            AxisMarks(position: .leading)
        }
        .padding()
        .frame(minWidth: 400, minHeight: 300)
    }
}

The window produced from the example is shown below. Notice, the label for the Y axis does not display properly.

wigging
  • 8,492
  • 12
  • 75
  • 117

1 Answers1

0

This issue seems to be caused by the space the label requires.

For example by adding the line .frame(minWidth: 55, minHeight: 50) to the rotated text, the issue gets solved (however, the label requires a lot of space, which I was not able to solve).

Updated chartYAxisLabel code:

 .chartYAxisLabel(position: .leading) {
                Text("The y-axis")
                    .rotationEffect(.degrees(180))
                    .frame(minWidth: 55, minHeight: 50)
        }

Updated preview:

updated graph)

Daniel
  • 20,420
  • 10
  • 92
  • 149