Skip to content

Chart Legends (SwiftUI)

A SwiftUI guide for coding agents. Also covers chart legend swiftui, hide chart legend, chartlegend position, chartforegroundstylescale, custom legend colors ios, swift charts series colors.

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
    ]
)

Use this guidance in your coding agent

Install the Better Design MCP once. Your agent then loads this page with one call.

get-swiftui-guide({ topic: "swiftui-mastering-charts-legends" })
claude mcp add --scope user better-design --transport http https://better-design.com/api/mcp --header "Authorization: Bearer <YOUR_API_KEY>"
Browse related design systems
Chart Legends (SwiftUI): SwiftUI guide for coding agents | Better Design