I am trying to create a SwiftUI line chart. By default the y-labels are drawn beside the grid lines. Thus the available space for the chart itself becomes smaller by the label width. To give the chart more space, I would like to move the label below the grid lines.
While this works using AxisValueLabel(anchor: .topLeading)
, the chart does not occupy the now freed space. Instead the chart keeps the same width as with the labels on the default positions.
How to change this?
var body: some View {
Chart {
ForEach(0..<data.count, id: \.self) { i in
LineMark(
x: .value("X", i+1),
y: .value("Value", data.values[i])
)
.foregroundStyle(.red)
.interpolationMethod(.catmullRom)
.lineStyle(StrokeStyle(lineWidth: 4))
}
}
.chartYScale(domain: [0, data.maxValue])
.chartYAxis {
AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in
AxisGridLine()
// Default Labels
// AxisValueLabel()
// Hide 0 Label and move others under the line
if value.index > 0 {
AxisValueLabel(anchor: .topLeading)
}
}
}
.frame(height: 300)
.padding()
}
This is controlled by the AxisMarks
. Use the .inset
preset to not have the axis labels occupy that extra space.
AxisMarks(preset: .inset, position: .leading, values: .automatic(desiredCount: 4)) { ... }