Skip to main content

Working with SwiftUI Charts

1. Creating Bar Charts

Property Value Description
Chart BarChart Displays data in vertical bars
Data Source ChartContent Defines the data to be visualized
Axis ChartAxis Configures X and Y axes for the chart

Example: Basic Bar Chart

import SwiftUI
import Charts

struct ContentView: View {
    let data = [10, 20, 30, 40, 50]

    var body: some View {
        Chart {
            ForEach(data.indices, id: \.self) { index in
                BarMark(
                    x: .value("Index", index),
                    y: .value("Value", data[index])
                )
            }
        }
    }
}

Example: Bar Chart with Labels

import SwiftUI
import Charts

struct LabeledBarChart: View {
    let salesData = [
        ("Q1", 100),
        ("Q2", 150),
        ("Q3", 200),
        ("Q4", 180)
    ]

    var body: some View {
        Chart {
            ForEach(salesData, id: \.0) { quarter, value in
                BarMark(
                    x: .value("Quarter", quarter),
                    y: .value("Sales", value)
                )
            }
        }
        .chartXAxis {
            AxisMarks(values: salesData.map { $0.0 }) { value in
                AxisGridLine()
                AxisTick()
                AxisValueLabel()
            }
        }
    }
}
Note: The BarMark is used to define each bar in the chart. You can customize the appearance using modifiers like foregroundStyle.

2. Creating Line Charts

Property Value Description
LineChart LineChart View type for rendering line charts in SwiftUI
chartData [ChartPoint] Array of data points to plot
chartStyle LineChartStyle Styling options for the line chart (e.g., color, thickness)

Example: Basic Line Chart

import SwiftUI
import Charts

struct ContentView: View {
    let data = [
        ChartPoint(x: 0, y: 10),
        ChartPoint(x: 1, y: 20),
        ChartPoint(x: 2, y: 15),
        ChartPoint(x: 3, y: 25)
    ]

    var body: some View {
        LineChart(data: data)
            .frame(height: 200)
    }
}

struct ChartPoint: Identifiable, Hashable {
    let id = UUID()
    let x: Double
    let y: Double
}

Example: Line Chart with Multiple Series

import SwiftUI
import Charts

struct MultiSeriesChartView: View {
    let series1 = [
        ChartPoint(x: 0, y: 10),
        ChartPoint(x: 1, y: 20),
        ChartPoint(x: 2, y: 15)
    ]
    
    let series2 = [
        ChartPoint(x: 0, y: 5),
        ChartPoint(x: 1, y: 15),
        ChartPoint(x: 2, y: 10)
    ]

    var body: some View {
        Chart {
            LineMark(
                x: \.x,
                y: \.y
            )
            .foregroundStyle(.blue)
            
            LineMark(
                x: \.x,
                y: \.y
            )
            .foregroundStyle(.red)
        }
        .frame(height: 200)
    }
}
Note: The ChartPoint struct must conform to Identifiable and Hashable for proper rendering in SwiftUI Charts.

3. Creating Point Charts

Property Description Example
PointChart Displays data points on a chart PointChart(data: dataPoints)
data Array of data points to display [Point(x: 1, y: 2), Point(x: 3, y: 4)]
xAxis Configuration for the x-axis AxisView(value: \.x)
yAxis Configuration for the y-axis AxisView(value: \.y)

Example: Basic Point Chart

import SwiftUI
import Charts

struct ContentView: View {
    let dataPoints = [
        Point(x: 1, y: 2),
        Point(x: 3, y: 4),
        Point(x: 5, y: 6)
    ]

    var body: some View {
        Chart {
            PointMark(
                x: \.x,
                y: \.y
            )
        }
        .frame(width: 300, height: 200)
    }
}

struct Point: Identifiable {
    let id = UUID()
    let x: Double
    let y: Double
}

4. Creating Area Charts

Property Value Description
Chart AreaChart Displays data as a filled area chart
Data Source ChartContent Defines the data to be visualized in the chart
Color Color Defines the color of the area chart

Example: Basic Area Chart

import SwiftUI
import Charts

struct ContentView: View {
    let data = [10, 20, 30, 40, 50]

    var body: some View {
        Chart {
            AreaMark(
                x: .value("Time", 1...5),
                y: .value("Value", data)
            )
        }
    }
}

Example: Customized Area Chart

import SwiftUI
import Charts

struct CustomAreaChart: View {
    let data = [
        ["month": "Jan", "value": 10],
        ["month": "Feb", "value": 25],
        ["month": "Mar", "value": 30],
        ["month": "Apr", "value": 45]
    ]

    var body: some View {
        Chart {
            AreaMark(
                x: .value("Month", data, key: "month"),
                y: .value("Value", data, key: "value")
            )
            .foregroundStyle(.blue)
        }
    }
}
Note: The AreaMark is used to create area charts in SwiftUI Charts. It requires a data source and can be customized with various styles.

5. Creating Rule Charts

Property Description Values
RuleChart Displays a chart with rules or thresholds RuleChart
rule Defines a horizontal rule in the chart Rule
value Value at which the rule is drawn Double

Example: Basic Rule Chart

import SwiftUI
import Charts

struct ContentView: View {
    let data = [10, 20, 30, 40, 50]

    var body: some View {
        Chart {
            BarMark(
                x: .value("Value", data),
                y: .value("Index", 0)
            )
            .foregroundStyle(.blue)

            RuleMark(y: .value("Threshold", 30))
                .foregroundStyle(.red)
        }
        .frame(height: 200)
    }
}
Note: Rule charts are useful for displaying thresholds or benchmarks in data visualization.

6. Customizing Chart Axes

Property Description Values
axis Defines the axis to customize .bottom, .leading, .top, .trailing
label Customizes the axis label Text("Label")
grid Configures grid lines for the axis .visible, .hidden
tick Customizes tick marks on the axis .visible, .hidden

Example: Customizing Chart Axes

Chart {
    LineMark(
        x: .value("Time", date),
        y: .value("Value", value)
    )
}
.axis(
    .bottom,
    .visible,
    label: Text("Time"),
    tick: .visible
)

7. Adding Chart Legends

Property Description Usage
chart.legend Defines the legend for a chart .chartLegend(.visible)
legendVisibility Controls whether the legend is visible or hidden .chartLegend(.hidden)

Example: Adding a Chart Legend

import SwiftUI
import Charts

struct ContentView: View {
    let data = [
        ChartPoint(x: 1, y: 10),
        ChartPoint(x: 2, y: 20),
        ChartPoint(x: 3, y: 15)
    ]

    var body: some View {
        Chart {
            LineMark(
                x: \.x,
                y: \.y
            )
        }
        .chartLegend(.visible)
    }
}

struct ChartPoint: Identifiable {
    let id = UUID()
    let x: Int
    let y: Int
}
Note: The chart legend is automatically generated from the chart's data and can be customized using .chartLegend.

8. Using Chart Annotations

Annotation Type Description Usage
LineAnnotation Draws a vertical or horizontal line on the chart LineAnnotation(value: 50, label: { Text("Threshold") })
RectangleAnnotation Draws a rectangle overlay on the chart area RectangleAnnotation(rect: CGRect(x: 10, y: 10, width: 50, height: 50), label: { Text("Region") })
TextAnnotation Places a text label at a specific point or area TextAnnotation(text: "Peak", position: .top, label: { Text("Peak") })

Example: Line Annotation in Chart

Chart(data: salesData) {
    LineMark(
        x: \.month,
        y: \.sales
    )
    LineAnnotation(value: 1000, label: { Text("Target") })
}

Example: Text Annotation in Chart

Chart(data: temperatureData) {
    LineMark(
        x: \.day,
        y: \.temperature
    )
    TextAnnotation(text: "High", position: .top, label: { Text("High Temp") })
}

9. Implementing Interactive Charts

Property Description Values
Chart Container for chart elements Chart
Plot Represents a single plot in the chart Plot
Point Represents a point in the chart Point
Axis Represents an axis in the chart Axis

Example: Basic Interactive Chart

import SwiftUI
import Charts

struct InteractiveChartView: View {
    @State private var data = [
        ChartPoint(x: 1, y: 10),
        ChartPoint(x: 2, y: 20),
        ChartPoint(x: 3, y: 15),
        ChartPoint(x: 4, y: 25)
    ]

    var body: some View {
        Chart {
            Plot {
                LineMark(
                    x: \.x,
                    y: \.y
                )
            }
        }
        .frame(height: 300)
    }
}

struct ChartPoint: Identifiable {
    let id = UUID()
    let x: Double
    let y: Double
}

Example: Chart with Interactive Selection

import SwiftUI
import Charts

struct InteractiveSelectionChartView: View {
    @State private var selectedPoint: ChartPoint?

    var body: some View {
        Chart {
            Plot {
                PointMark(
                    x: \.x,
                    y: \.y
                )
                .foregroundStyle(.blue)
            }
            .onTapGesture { point in
                selectedPoint = point
            }
        }
        .frame(height: 300)
    }
}
Note: The onTapGesture modifier allows for interaction with chart elements.
Warning: Ensure that the chart data is properly structured to support interactive features.

Key Features of Interactive Charts

  • Tap gestures for point selection
  • Hover effects for data insight
  • Zoom and pan capabilities
  • Custom styling for visual elements

10. Styling Charts with Modifiers

Modifier Description Example
chartStyle(_ style: ChartStyle) Applies a predefined chart style to the entire chart ChartStyle.default
foregroundStyle(_ style: Style) Changes the foreground color of chart elements .foregroundStyle(.blue)
backgroundStyle(_ style: Style) Sets the background color or image of the chart .backgroundStyle(.gray)
frame(width: CGFloat?, height: CGFloat?) Sets the size of the chart view .frame(width: 300, height: 200)
aspectRatio(_ ratio: CGFloat?, contentMode: ContentMode) Defines the aspect ratio of the chart .aspectRatio(1.5, contentMode: .fit)

Example: Applying Chart Modifiers

import SwiftUI

struct ContentView: View {
    var body: some View {
        Chart {
            LineMark(
                x: \.time,
                y: \.value
            )
        }
        .chartStyle(.default)
        .foregroundStyle(.blue)
        .backgroundStyle(.gray)
        .frame(width: 300, height: 200)
    }
}
Note: Chart modifiers can be chained to apply multiple styles and layouts to a chart.

Was this article helpful?