Swift Charts generates a legend automatically whenever a mark uses foregroundStyle(by:) to
split a series. Two modifiers control it: chartLegend for visibility and placement, and
chartForegroundStyleScale for the colors it shows.
The Automatic Legend
Styling a mark by a data value is what creates the legend. Nothing else is required.
Chart {
ForEach(stats, id: \.city) { stat in
BarMark(
x: .value("City", stat.city),
y: .value("Population", stat.population)
)
.foregroundStyle(by: .value("Gender", stat.gender))
.position(by: .value("Gender", stat.gender))
}
}
Visibility and Placement
chartLegend takes automatic, visible, or hidden. Another overload places the legend.
Chart { /* ... */ }
.chartLegend(.hidden)
Chart { /* ... */ }
.chartLegend(position: .top, alignment: .leading, spacing: 8)
Custom Colors
chartForegroundStyleScale pairs with foregroundStyle(by:) and maps each domain value to a
color, on the marks and in the legend at once.
Chart { /* ... */ }
.chartForegroundStyleScale(
domain: Gender.allCases,
range: [.red, .orange, .black]
)
A dictionary overload sets the mapping explicitly per value, which helps when the pairing must not depend on the order of the domain.
.chartForegroundStyleScale(
[
Gender.notSet: Color.black,
.female: Color.orange,
.male: Color.red
]
)