The Swift Charts framework exposes view modifiers that restyle a Chart without redrawing it
yourself. chartPlotStyle styles the plot area, and chartXAxis and chartYAxis rebuild an axis
from AxisMarks.
Plot Area
chartPlotStyle hands you the plot content as a plain SwiftUI view, so any modifier applies.
Chart {
// ...
}
.chartPlotStyle { chartContent in
chartContent
.background(Color.secondary.opacity(0.2))
.frame(height: 32)
}
Size the plot here, not on the Chart itself. A frame on the Chart also constrains the
legend, which is rarely what you want.
Axis Presets
chartXAxis and chartYAxis take an AxisContentBuilder closure. The simple AxisMarks
initializer configures the whole axis at once: preset, position, values, and stroke.
Chart {
// ...
}
.chartXAxis {
AxisMarks(
preset: .aligned,
position: .bottom,
values: .stride(by: 500),
stroke: StrokeStyle(lineWidth: 4, lineCap: .butt, lineJoin: .bevel)
)
}
The preset parameter accepts automatic, aligned, inset, and extended, which change how
the framework places values along the axis. The values parameter generates the marks, here with
stride(by:).
Per-Value Axis Composition
Another AxisMarks initializer gives you each value, so you compose the axis from
AxisGridLine, AxisValueLabel, and AxisTick and vary them per value.
.chartXAxis {
AxisMarks(values: .stride(by: 500)) { value in
AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 4))
AxisValueLabel(anchor: .topTrailing)
if let value = value.as(Int.self), value % 2 == 0 {
AxisTick(centered: true, length: 10)
}
}
}
Read the concrete value with value.as(Int.self) to decide which components a mark gets, for
example a tick on every second value only.