Search code examples
iosswiftuicharts

Positioning axis labels


This is the x-axis of a SwiftUI Chart:

enter image description here

As you can see the vertical gridlines cross the x-axis and the labels (1,735 etc) are drawn to the right of the lines.

I would like the gridlines to stop at the x-axis and have the labels centered below it.

Is that possible?

I am now using the following modifiers:

.chartXAxisLabel(position: .bottom, alignment: .center) {
    Text("x axis title")
}
.chartXScale(domain: [minX, maxX])

Solution

  • Try adding a .chartXAxis modifier to define the AxisMarks:

    • include AxisGridLine to have the lines included
    • omit AxisTick if you don't want axis ticks below the grid lines
    • set an anchor of .top for the labels.

    Like this:

    .chartXAxis {
        AxisMarks(position: .bottom, values: .automatic) { _ in
            AxisGridLine()
            AxisValueLabel(anchor: .top)
        }
    }
    

    See Customizing axes in Swift Charts for detailed documentation.