Contents

Chart

A SwiftUI view that displays a chart.

Declaration

@MainActor @preconcurrency struct Chart<Content> where Content : ChartContent

Mentioned in

Overview

To create a chart, instantiate a Chart structure with marks that display the properties of your data. For example, suppose you have an array of ValuePerCategory structures that define data points composed of a category and a value:

struct ValuePerCategory {
    var category: String
    var value: Double
}

let data: [ValuePerCategory] = [
    .init(category: "A", value: 5),
    .init(category: "B", value: 9),
    .init(category: "C", value: 7)
]

You can use BarMark inside a chart to represent the category property as different bars in the chart and the value property as the y value for each bar:

Chart(data, id: \.category) { item in
    BarMark(
        x: .value("Category", item.category),
        y: .value("Value", item.value)
    )
}

This chart initializer behaves a lot like a SwiftUI ForEach, creating a mark — in this case, a bar — for each of the values in the data array:

[Image]

Controlling data series inside a chart

You can compose more sophisticated charts by providing more than one series of marks to the chart. For example, suppose you have profit data for two companies:

struct ProfitOverTime {
    var date: Date
    var profit: Double
}

let departmentAProfit: [ProfitOverTime] = <#Profit array A#>
let departmentBProfit: [ProfitOverTime] = <#Profit array B#>

The following chart creates two different series of LineMark instances with different colors to represent the data for each company. In effect, it moves the ForEach construct from the chart’s initializer into the body of the chart, enabling you to represent multiple different series:

Chart {
    ForEach(departmentAProfit, id: \.date) { item in
        LineMark(
            x: .value("Date", item.date),
            y: .value("Profit A", item.profit),
            series: .value("Company", "A")
        )
        .foregroundStyle(.blue)
    }
    ForEach(departmentBProfit, id: \.date) { item in
        LineMark(
            x: .value("Date", item.date),
            y: .value("Profit B", item.profit),
            series: .value("Company", "B")
        )
        .foregroundStyle(.green)
    }
    RuleMark(
        y: .value("Threshold", 400)
    )
    .foregroundStyle(.red)
}

You indicate which series a line mark belongs to by specifying its series input parameter. The above chart also uses a RuleMark to produce a horizontal line segment that displays a constant threshold value across the width of the chart:

[Image]

Topics

Creating a chart

Supporting types

See Also

Charts