
Swift Charts
- 2.8k installs
- 944 repo stars
- Updated July 15, 2026
- dpearson2699/swift-ios-skills
swift-charts is a skill for Swift Charts bar, line, area, pie, scrollable, and 3D visualizations on iOS 26 plus.
About
Swift Charts helps implement and review data visualizations targeting iOS 26 and later using Chart and Chart3D containers with marks such as BarMark, LineMark, PointMark, AreaMark, RuleMark, RectangleMark, and SectorMark. Workflow starts from Identifiable data models, mark selection, foregroundStyle encoding, axis customization, scale domains, and optional selection or scrolling modifiers. Vectorized plots including BarPlot and LinePlot optimize one thousand plus point series on iOS 18. Chart3D and SurfacePlot cover spatial and surface data on iOS 26. Selection APIs bind chartXSelection, chartAngleSelection, and range selection for interactive drill-down. Scrollable charts use chartScrollableAxes, chartXVisibleDomain, and chartScrollPosition for dense time series. Axis customization covers hidden axes, stride-based ticks, axis labels, and logarithmic scale domains. Annotations attach to RuleMark thresholds, and the skill includes common mistakes, accessibility guidance, and a review checklist for existing chart code.
- Chart container patterns for single and multi-series data.
- Mark types from BarMark through SectorMark pie and donut.
- Selection and scrollable chart modifiers for iOS 17 plus.
- Vectorized plots for one thousand plus 2D points.
- Chart3D and SurfacePlot for iOS 26 spatial data.
Swift Charts by the numbers
- 2,805 all-time installs (skills.sh)
- +124 installs in the week ending Jul 29, 2026 (Skillselion tracking)
- Ranked #64 of 1,039 Mobile Development skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 31, 2026 (Skillselion catalog sync)
swift-charts capabilities & compatibility
- Capabilities
- chart and chart3d container setup · mark type selection and multi series encoding · axis, scale, legend, and annotation configuratio · point and range selection modifiers · scrollable time series chart patterns · vectorized plot optimization for large datasets
- Use cases
- frontend · data analysis
- Pricing
- Free
What swift-charts says it does
Build data visualizations with Swift Charts targeting iOS 26+
For 1000+ 2D data points, use vectorized plots
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill swift-chartsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.8k |
|---|---|
| repo stars | ★ 944 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 15, 2026 |
| Repository | dpearson2699/swift-ios-skills ↗ |
How do I build interactive Swift Charts with correct marks, axes, scales, and selection?
Implement Swift Charts bar, line, area, point, pie, scrollable, and iOS 26 3D visualizations with axes, selection, and annotations.
Who is it for?
iOS developers adding dashboards, analytics, or spatial charts with Swift Charts.
Skip if: Skip for UIKit-only chart libraries, Android charts, or web D3 visualizations.
When should I use this skill?
User implements Swift Charts, BarMark, selection, scrollable axes, or Chart3D surface plots.
What you get
Working Chart or Chart3D view with axes, encoding, and optional selection or scrolling.
- SwiftUI Chart views
- Axis and scale configuration
- Accessible chart marks with selection
By the numbers
- Recommends vectorized plots for datasets exceeding 1000 data points
- Documents 9 common Swift Charts mistakes with code examples
- Includes a 15-item chart review checklist in the skill body
Files
Swift Charts
Build data visualizations with Swift Charts targeting iOS 26+. Compose marks inside Chart or Chart3D, configure axes and scales with view modifiers, and use vectorized plots or 3D plots when the data calls for them.
See references/charts-patterns.md for extended patterns, 3D charts, accessibility, and theming guidance.
Contents
- Workflow
- Chart Container
- Mark Types
- Axis Customization
- Scale Configuration
- Foreground Style and Encoding
- Selection (iOS 17+)
- Scrollable Charts (iOS 17+)
- Annotations
- Legend
- Vectorized Plots (iOS 18+)
- 3D Charts (iOS 26+)
- Common Mistakes
- Review Checklist
- References
Workflow
1. Build a new chart
1. Define data as an Identifiable struct or use id: key path. 2. Choose mark type(s): BarMark, LineMark, PointMark, AreaMark, RuleMark, RectangleMark, SectorMark, or SurfacePlot. 3. Wrap 2D marks in Chart; use Chart3D only for real spatial or surface data. 4. Encode visual channels: .foregroundStyle(by:), .symbol(by:), .lineStyle(by:). 5. Configure axes with .chartXAxis / .chartYAxis. 6. Set scale domains with .chartXScale(domain:) / .chartYScale(domain:). 7. Add selection, scrolling, or annotations as needed. 8. For 1000+ 2D data points, use vectorized plots (BarPlot, LinePlot, etc.).
2. Review existing chart code
Run through the Review Checklist at the end of this file.
Chart Container
// Data-driven init (single-series)
Chart(sales) { item in
BarMark(x: .value("Month", item.month), y: .value("Revenue", item.revenue))
}
// Content closure init (multi-series, mixed marks)
Chart {
ForEach(seriesA) { item in
LineMark(x: .value("Date", item.date), y: .value("Value", item.value))
.foregroundStyle(.blue)
}
RuleMark(y: .value("Target", 500))
.foregroundStyle(.red)
}
// Custom ID key path
Chart(data, id: \.category) { item in
BarMark(x: .value("Category", item.category), y: .value("Count", item.count))
}Mark Types
BarMark (iOS 16+)
// Vertical bar
BarMark(x: .value("Month", item.month), y: .value("Sales", item.sales))
// Stacked by category (automatic when same x maps to multiple bars)
BarMark(x: .value("Month", item.month), y: .value("Sales", item.sales))
.foregroundStyle(by: .value("Product", item.product))
// Horizontal bar
BarMark(x: .value("Sales", item.sales), y: .value("Month", item.month))
// Interval bar (Gantt chart)
BarMark(
xStart: .value("Start", item.start),
xEnd: .value("End", item.end),
y: .value("Task", item.task)
)LineMark (iOS 16+)
// Single line
LineMark(x: .value("Date", item.date), y: .value("Price", item.price))
// Multi-series via foregroundStyle encoding
LineMark(x: .value("Date", item.date), y: .value("Temp", item.temp))
.foregroundStyle(by: .value("City", item.city))
.interpolationMethod(.catmullRom)
// Multi-series with explicit series parameter
LineMark(
x: .value("Date", item.date),
y: .value("Price", item.price),
series: .value("Ticker", item.ticker)
)PointMark (iOS 16+)
PointMark(x: .value("Height", item.height), y: .value("Weight", item.weight))
.foregroundStyle(by: .value("Species", item.species))
.symbol(by: .value("Species", item.species))
.symbolSize(100)AreaMark (iOS 16+)
// Stacked area
AreaMark(x: .value("Date", item.date), y: .value("Sales", item.sales))
.foregroundStyle(by: .value("Category", item.category))
// Range band
AreaMark(
x: .value("Date", item.date),
yStart: .value("Min", item.min),
yEnd: .value("Max", item.max)
)
.opacity(0.3)RuleMark (iOS 16+)
RuleMark(y: .value("Target", 9000))
.foregroundStyle(.red)
.lineStyle(StrokeStyle(dash: [5, 3]))
.annotation(position: .top, alignment: .leading) {
Text("Target").font(.caption).foregroundStyle(.red)
}RectangleMark (iOS 16+)
RectangleMark(x: .value("Hour", item.hour), y: .value("Day", item.day))
.foregroundStyle(by: .value("Intensity", item.intensity))SectorMark (iOS 17+)
Use SectorMark for strictly positive values; filter, aggregate, or explain zero/negative values outside the pie or donut.
// Pie chart
Chart(data, id: \.name) { item in
SectorMark(angle: .value("Sales", item.sales))
.foregroundStyle(by: .value("Category", item.name))
}
// Donut chart
Chart(data, id: \.name) { item in
SectorMark(
angle: .value("Sales", item.sales),
innerRadius: .ratio(0.618),
outerRadius: .inset(10),
angularInset: 1
)
.cornerRadius(4)
.foregroundStyle(by: .value("Category", item.name))
}Axis Customization
// Hide axes
.chartXAxis(.hidden)
.chartYAxis(.hidden)
// Custom axis content
.chartXAxis {
AxisMarks(values: .stride(by: .month)) { value in
AxisGridLine()
AxisTick()
AxisValueLabel(format: .dateTime.month(.abbreviated))
}
}
// Multiple AxisMarks compositions (different intervals for grid vs. labels)
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { _ in AxisGridLine() }
AxisMarks(values: .stride(by: .week)) { _ in
AxisTick()
AxisValueLabel(format: .dateTime.week())
}
}
// Axis labels (titles)
.chartXAxisLabel("Time", position: .bottom, alignment: .center)
.chartYAxisLabel("Revenue ($)", position: .leading, alignment: .center)Scale Configuration
.chartYScale(domain: 0...100) // Explicit numeric domain
.chartYScale(domain: .automatic(includesZero: true)) // Include zero
.chartYScale(domain: 1...10000, type: .log) // Logarithmic scale
.chartXScale(domain: ["Mon", "Tue", "Wed", "Thu"]) // Categorical orderingForeground Style and Encoding
BarMark(...).foregroundStyle(.blue) // Static color
BarMark(...).foregroundStyle(by: .value("Category", item.category)) // Data encoding
AreaMark(...).foregroundStyle( // Gradient
.linearGradient(colors: [.blue, .cyan], startPoint: .bottom, endPoint: .top)
)Selection (iOS 17+)
@State private var selectedDate: Date?
@State private var selectedRange: ClosedRange<Date>?
@State private var selectedAngle: Double?
// Point selection
Chart(data) { item in
LineMark(x: .value("Date", item.date), y: .value("Value", item.value))
}
.chartXSelection(value: $selectedDate)
// Range selection
.chartXSelection(range: $selectedRange)
// Angular selection binds the plottable angle value; derive the category from ranges.
.chartAngleSelection(value: $selectedAngle)Scrollable Charts (iOS 17+)
Chart(dailyData) { item in
BarMark(x: .value("Date", item.date, unit: .day), y: .value("Steps", item.steps))
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 3600 * 24 * 7) // 7 days visible
.chartScrollPosition(initialX: latestDate)
.chartScrollTargetBehavior(
.valueAligned(matching: DateComponents(hour: 0), majorAlignment: .page)
)Annotations
BarMark(x: .value("Month", item.month), y: .value("Sales", item.sales))
.annotation(position: .top, alignment: .center, spacing: 4) {
Text("\(item.sales, format: .number)").font(.caption2)
}
// Overflow resolution
.annotation(
position: .top,
overflowResolution: .init(x: .fit(to: .chart), y: .padScale)
) { Text("Label") }Legend
.chartLegend(.hidden) // Hide
.chartLegend(position: .bottom, alignment: .center, spacing: 10) // Position
.chartLegend(position: .bottom) { // Custom
HStack {
ForEach(categories, id: \.self) { cat in
Label(cat, systemImage: "circle.fill").font(.caption)
}
}
}Vectorized Plots (iOS 18+)
Use for large datasets (1000+ points). Accept entire collections or functions.
// Data-driven
Chart {
BarPlot(sales, x: .value("Month", \.month), y: .value("Revenue", \.revenue))
.foregroundStyle(\.barColor)
}
// Function plotting: y = f(x)
Chart {
LinePlot(x: "x", y: "y", domain: -5...5) { x in sin(x) }
}
// Parametric: (x, y) = f(t)
Chart {
LinePlot(x: "x", y: "y", t: "t", domain: 0...(2 * .pi)) { t in
(x: cos(t), y: sin(t))
}
}Apply KeyPath-based modifiers before simple-value modifiers:
BarPlot(data, x: .value("X", \.x), y: .value("Y", \.y))
.foregroundStyle(\.color) // KeyPath first
.opacity(0.8) // Value modifier second3D Charts (iOS 26+)
Use Chart3D for spatial data or bivariate surfaces, not as a decorative replacement for ordinary 2D categorical or time-series charts. Chart3D accepts SurfacePlot plus 3D initializers of PointMark, RuleMark, and RectangleMark.
@State private var pose: Chart3DPose = .default
Chart3D {
SurfacePlot(x: "x", y: "y", z: "z") { x, z in
sin(2 * x) * cos(2 * z)
}
.foregroundStyle(.heightBased)
}
.chartXScale(domain: -2...2)
.chartYScale(domain: -1...1)
.chartZScale(domain: -2...2)
.chart3DPose($pose)Common Mistakes
1. Missing series parameter for multi-line charts
// WRONG -- all points connect into one line
Chart {
ForEach(allCities) { item in
LineMark(x: .value("Date", item.date), y: .value("Temp", item.temp))
}
}
// CORRECT -- separate lines per city
Chart {
ForEach(allCities) { item in
LineMark(x: .value("Date", item.date), y: .value("Temp", item.temp))
.foregroundStyle(by: .value("City", item.city))
}
}2. Too many SectorMark slices
// WRONG -- 20 tiny sectors are unreadable
Chart(twentyCategories, id: \.name) { item in
SectorMark(angle: .value("Value", item.value))
}
// CORRECT -- group into top 5 + "Other"
Chart(groupedData, id: \.name) { item in
SectorMark(angle: .value("Value", item.value))
.foregroundStyle(by: .value("Category", item.name))
}3. Missing scale domain when zero-baseline matters
// WRONG -- axis starts at ~95; small changes look dramatic
Chart(data) {
LineMark(x: .value("Day", $0.day), y: .value("Score", $0.score))
}
// CORRECT -- explicit domain for honest representation
Chart(data) {
LineMark(x: .value("Day", $0.day), y: .value("Score", $0.score))
}
.chartYScale(domain: 0...100)4. Static foregroundStyle overriding data encoding
// WRONG -- static color overrides by-value encoding
BarMark(x: .value("X", item.x), y: .value("Y", item.y))
.foregroundStyle(by: .value("Category", item.category))
.foregroundStyle(.blue)
// CORRECT -- use only the data encoding
BarMark(x: .value("X", item.x), y: .value("Y", item.y))
.foregroundStyle(by: .value("Category", item.category))5. Individual marks for 10,000+ data points
// WRONG -- creates 10,000 mark views; slow
Chart(largeDataset) { item in
PointMark(x: .value("X", item.x), y: .value("Y", item.y))
}
// CORRECT -- vectorized plot (iOS 18+)
Chart {
PointPlot(largeDataset, x: .value("X", \.x), y: .value("Y", \.y))
}6. Fixed chart height breaking Dynamic Type
// WRONG -- clips axis labels at large text sizes
Chart(data) { ... }
.frame(height: 200)
// CORRECT -- adaptive sizing
Chart(data) { ... }
.frame(minHeight: 200, maxHeight: 400)7. KeyPath modifier after value modifier on vectorized plots
// WRONG -- compiler error
BarPlot(data, x: .value("X", \.x), y: .value("Y", \.y))
.opacity(0.8)
.foregroundStyle(\.color)
// CORRECT -- KeyPath modifiers first
BarPlot(data, x: .value("X", \.x), y: .value("Y", \.y))
.foregroundStyle(\.color)
.opacity(0.8)8. Missing accessibility labels
// WRONG -- VoiceOver users get no context
Chart(data) {
BarMark(x: .value("Month", $0.month), y: .value("Sales", $0.sales))
}
// CORRECT -- add per-mark accessibility
Chart(data) { item in
BarMark(x: .value("Month", item.month), y: .value("Sales", item.sales))
.accessibilityLabel("\(item.month)")
.accessibilityValue("\(item.sales) units sold")
}9. Treating angle selection as category selection
chartAngleSelection(value:) binds the selected plottable angle value. For pie and donut charts, map that numeric value through cumulative sector ranges before comparing it to a category label.
Review Checklist
- [ ] Data model uses
Identifiableor chart usesid:key path - [ ] Mark type matches goal (bar=comparison, line=trend, sector=proportion)
- [ ] Multi-series lines use
series:parameter or.foregroundStyle(by:) - [ ] Axes configured with appropriate labels, ticks, and grid lines
- [ ] Scale domain set explicitly when zero-baseline matters
- [ ] Pie/donut uses positive values, 5-7 sectors, and "Other" grouping
- [ ] Selection binding type matches axis data type (
Date?for date axis) - [ ] Pie/donut angle selection maps numeric angle values back to categories
- [ ] Scrollable charts set
.chartXVisibleDomain(length:)for viewport - [ ] Vectorized plots used for datasets exceeding 1000 points
- [ ] KeyPath modifiers applied before value modifiers on vectorized plots
- [ ]
Chart3Dused only for real 3D data or surfaces, with z scale and pose reviewed - [ ] Accessibility labels added to marks for VoiceOver
- [ ] Chart tested with Dynamic Type and Dark Mode
- [ ] Legend visible and positioned, or intentionally hidden
- [ ] Ensure chart data model types are Sendable; update chart data on @MainActor
References
- Extended patterns: references/charts-patterns.md
- Apple docs: Swift Charts
- Apple docs: Creating a chart using Swift Charts
- Apple docs: Swift Charts updates
- Apple docs: Chart3D
- Apple docs: SurfacePlot
{
"skill_name": "swift-charts",
"evals": [
{
"id": 0,
"name": "chart3d-surface-setup",
"prompt": "We are targeting iOS 26 and need an interactive scientific visualization for z-depth data: render y = sin(2x) * cos(2z) as a 3D surface, keep the axes stable, and let the user inspect the view. What Swift Charts API should we use and what code shape should I start from?",
"expected_output": "Recommends Chart3D with SurfacePlot, labels x/y/z correctly, sets explicit x/y/z scale domains, binds Chart3DPose for inspection, and avoids using a 2D LinePlot/AreaPlot for the bivariate surface.",
"files": [],
"expectations": [
"Uses Chart3D and SurfacePlot for the iOS 26 bivariate surface instead of a 2D Chart with LinePlot or AreaPlot.",
"Shows or describes SurfacePlot with x, y, and z labels and a closure of the form y = f(x, z).",
"Sets or recommends explicit chartXScale, chartYScale, and chartZScale domains for stable comparisons.",
"Mentions Chart3DPose or chart3DPose for interactive inspection.",
"Notes that Chart3D should be used for real spatial or surface data, not as decoration for ordinary 2D charts."
]
},
{
"id": 1,
"name": "angle-selection-review",
"prompt": "Review this Swift Charts donut snippet: `@State private var selectedProduct: String?`; each `SectorMark(angle: .value(\"Sales\", item.sales))` sets opacity by comparing `selectedProduct == item.name`; the chart ends with `.chartAngleSelection(value: $selectedProduct)`. It compiles strangely. What is wrong and how should we fix the selection model?",
"expected_output": "Explains that chartAngleSelection binds the selected plottable angle value, uses a numeric binding such as Double?, maps the value back to a category with cumulative sector ranges, and keeps normal SectorMark pie/donut readability guidance.",
"files": [],
"expectations": [
"States that chartAngleSelection(value:) binds a Plottable angle value rather than the sector's category string.",
"Replaces the String? selection binding with a numeric angle binding such as Double?.",
"Maps the selected angle through cumulative sales/value ranges to derive the selected product/category.",
"Keeps SectorMark readability guidance such as positive values, limiting to 5-7 sectors, or grouping small slices into Other.",
"Does not route this bug to generic SwiftUI state management as the primary fix."
]
},
{
"id": 2,
"name": "boundary-routing",
"prompt": "A dashboard request mixes Swift Charts, MapKit annotations, NavigationStack deep links, async data loading, @Observable model ownership, and a custom VoiceOver audit. Split what belongs in the swift-charts skill versus adjacent Apple skills, then give the chart-specific recommendations.",
"expected_output": "Keeps chart construction, marks, axes/scales, selection/scrolling, vectorized plots, Chart3D, and chart accessibility basics in swift-charts while routing map annotations, navigation, data loading, Observation architecture, and detailed accessibility audits to sibling skills.",
"files": [],
"expectations": [
"Keeps Swift Charts chart type selection, marks, axes/scales, legends, annotations, selection, scrolling, vectorized plots, and Chart3D guidance in swift-charts scope.",
"Routes MapKit annotations or map overlays to MapKit guidance rather than treating them as chart marks.",
"Routes NavigationStack/deep-link implementation to swiftui-navigation.",
"Routes async networking/data loading and @Observable model ownership details to the appropriate networking, concurrency, or SwiftUI architecture skills.",
"Routes a deep VoiceOver/accessibility audit to ios-accessibility while still giving chart-specific label, color, Dynamic Type, and audio graph considerations."
]
}
]
}
Swift Charts Patterns Reference
Extended patterns, accessibility guidance, and theming for Swift Charts on iOS 26+. Import Charts in every file that uses these APIs.
import SwiftUI
import Charts---
Contents
- Data Modeling
- Bar Chart Patterns
- Line Chart Patterns
- Pie and Donut Chart Patterns (SectorMark, iOS 17+)
- Combined Chart Patterns
- Chart Selection with Overlay Annotation
- Scrollable Chart with Visible Domain
- Function Plotting (LinePlot, iOS 18+)
- 3D Charts and Surfaces (Chart3D, iOS 26+)
- Accessibility
- Dynamic Type and Color Considerations
- Performance: Vectorized Plots for Large Datasets
- Dark Mode and Theming
- Heat Map Pattern
- Stacking Methods
- MarkDimension Options
- Symbol Configuration
- ChartProxy and Coordinate Conversion
- Quick Reference: Chart View Modifiers
- Apple Documentation Links
Data Modeling
Use @Observable for chart data models. Pair with @State in views.
@Observable
class SalesModel {
var monthlySales: [MonthlySale] = []
func load() async {
monthlySales = await SalesService.fetchMonthlySales()
}
}
struct MonthlySale: Identifiable {
let id = UUID()
let month: Date
let revenue: Double
let category: String
}struct SalesDashboard: View {
@State private var model = SalesModel()
var body: some View {
Chart(model.monthlySales) { item in
BarMark(
x: .value("Month", item.month, unit: .month),
y: .value("Revenue", item.revenue)
)
.foregroundStyle(by: .value("Category", item.category))
}
.task { await model.load() }
}
}---
Bar Chart Patterns
Simple vertical bars
Chart(data) { item in
BarMark(
x: .value("Department", item.department),
y: .value("Revenue", item.revenue)
)
}Stacked bars (automatic)
When multiple bars share the same x value, they stack automatically:
Chart(data) { item in
BarMark(
x: .value("Quarter", item.quarter),
y: .value("Sales", item.sales)
)
.foregroundStyle(by: .value("Product", item.product))
}Grouped bars
Use .position(by:) to place bars side by side instead of stacking:
Chart(data) { item in
BarMark(
x: .value("Quarter", item.quarter),
y: .value("Sales", item.sales)
)
.foregroundStyle(by: .value("Product", item.product))
.position(by: .value("Product", item.product))
}Horizontal bars
Swap the x and y axes:
Chart(data) { item in
BarMark(
x: .value("Sales", item.sales),
y: .value("Region", item.region)
)
}
.chartYAxis {
AxisMarks { _ in
AxisValueLabel()
}
}Normalized stacked bars (100%)
Chart(data) { item in
BarMark(
x: .value("Quarter", item.quarter),
y: .value("Sales", item.sales),
stacking: .normalized
)
.foregroundStyle(by: .value("Product", item.product))
}Bar with annotation
Chart(data) { item in
BarMark(
x: .value("Month", item.month),
y: .value("Revenue", item.revenue)
)
.annotation(position: .top, alignment: .center, spacing: 4) {
Text(item.revenue, format: .currency(code: "USD").precision(.fractionLength(0)))
.font(.caption2)
}
}Gantt chart (interval bars)
Chart(tasks) { task in
BarMark(
xStart: .value("Start", task.startDate),
xEnd: .value("End", task.endDate),
y: .value("Task", task.name)
)
.foregroundStyle(by: .value("Status", task.status))
}---
Line Chart Patterns
Single line with points
Chart(data) { item in
LineMark(
x: .value("Date", item.date),
y: .value("Price", item.price)
)
PointMark(
x: .value("Date", item.date),
y: .value("Price", item.price)
)
.symbolSize(30)
}Multi-series lines
Chart(temperatures) { item in
LineMark(
x: .value("Date", item.date),
y: .value("Temp", item.temperature)
)
.foregroundStyle(by: .value("City", item.city))
.symbol(by: .value("City", item.city))
}Line with area fill
Chart(data) { item in
AreaMark(
x: .value("Date", item.date),
y: .value("Value", item.value)
)
.foregroundStyle(
.linearGradient(
colors: [.blue.opacity(0.3), .blue.opacity(0.05)],
startPoint: .top,
endPoint: .bottom
)
)
LineMark(
x: .value("Date", item.date),
y: .value("Value", item.value)
)
.foregroundStyle(.blue)
}Interpolation methods
| Method | Use Case |
|---|---|
.linear | Default; straight segments between points |
.monotone | Smooth curve that preserves monotonicity |
.catmullRom | Smooth general-purpose curve |
.cardinal | Smooth with adjustable tension |
.stepStart | Step function starting at data point |
.stepCenter | Step function centered on data point |
.stepEnd | Step function ending at data point |
LineMark(x: .value("X", item.x), y: .value("Y", item.y))
.interpolationMethod(.monotone)Sparkline (minimal inline chart)
Chart(recentData) { item in
LineMark(
x: .value("Time", item.time),
y: .value("Value", item.value)
)
.interpolationMethod(.catmullRom)
}
.chartXAxis(.hidden)
.chartYAxis(.hidden)
.chartLegend(.hidden)
.frame(width: 80, height: 30)---
Pie and Donut Chart Patterns (SectorMark, iOS 17+)
Use strictly positive values for sectors. Filter, aggregate, or show zero and negative values outside the pie or donut so angular sizes remain meaningful.
Basic pie chart
Chart(products, id: \.name) { item in
SectorMark(angle: .value("Sales", item.sales))
.foregroundStyle(by: .value("Product", item.name))
}Donut chart with golden ratio inner radius
Chart(products, id: \.name) { item in
SectorMark(
angle: .value("Sales", item.sales),
innerRadius: .ratio(0.618),
outerRadius: .inset(10),
angularInset: 1
)
.cornerRadius(4)
.foregroundStyle(by: .value("Product", item.name))
}Donut chart with center label
Chart(products, id: \.name) { item in
SectorMark(
angle: .value("Sales", item.sales),
innerRadius: .ratio(0.618),
angularInset: 1
)
.cornerRadius(4)
.foregroundStyle(by: .value("Product", item.name))
}
.chartBackground { _ in
VStack {
Text("Total")
.font(.caption)
.foregroundStyle(.secondary)
Text("\(totalSales, format: .number)")
.font(.title2.bold())
}
}Angular selection on donut
struct ProductSales: Identifiable {
let id = UUID()
let name: String
let sales: Double
}
@State private var selectedAngle: Double?
var selectedProduct: ProductSales? {
guard let selectedAngle else { return nil }
var runningTotal = 0.0
return products.first { product in
let range = runningTotal..<(runningTotal + product.sales)
runningTotal += product.sales
return range.contains(selectedAngle)
}
}
Chart(products, id: \.name) { item in
SectorMark(
angle: .value("Sales", item.sales),
innerRadius: .ratio(0.618),
angularInset: 1
)
.cornerRadius(4)
.foregroundStyle(by: .value("Product", item.name))
.opacity(selectedProduct == nil || selectedProduct?.name == item.name ? 1.0 : 0.4)
}
.chartAngleSelection(value: $selectedAngle)chartAngleSelection(value:) binds the selected plottable angle value, not the sector label. Convert that value through cumulative sector ranges before using it to highlight or annotate a category.
Grouping small slices
Limit pie/donut charts to 5-7 positive-value sectors. Group the rest into "Other":
func groupSmallSlices(_ data: [CategorySales], topN: Int = 5) -> [CategorySales] {
let sorted = data.sorted { $0.sales > $1.sales }
let top = Array(sorted.prefix(topN))
let otherTotal = sorted.dropFirst(topN).reduce(0) { $0 + $1.sales }
guard otherTotal > 0 else { return top }
return top + [CategorySales(name: "Other", sales: otherTotal)]
}---
Combined Chart Patterns
Line + area (trend with fill)
Chart(data) { item in
AreaMark(
x: .value("Date", item.date),
yStart: .value("Min", item.low),
yEnd: .value("Max", item.high)
)
.foregroundStyle(.blue.opacity(0.15))
LineMark(
x: .value("Date", item.date),
y: .value("Average", item.average)
)
.foregroundStyle(.blue)
.lineStyle(StrokeStyle(lineWidth: 2))
}Bar + threshold rule
Chart {
ForEach(data) { item in
BarMark(
x: .value("Month", item.month),
y: .value("Revenue", item.revenue)
)
}
RuleMark(y: .value("Target", targetRevenue))
.foregroundStyle(.red)
.lineStyle(StrokeStyle(lineWidth: 1, dash: [5, 3]))
.annotation(position: .top, alignment: .leading) {
Text("Target: \(targetRevenue, format: .number)")
.font(.caption)
.foregroundStyle(.red)
}
}Scatter + trend line
Chart {
ForEach(data) { item in
PointMark(
x: .value("Experience", item.yearsExperience),
y: .value("Salary", item.salary)
)
.opacity(0.6)
}
LinePlot(x: "Experience", y: "Salary", domain: 0...20) { x in
baseSalary + x * salaryPerYear // linear trend
}
.foregroundStyle(.red)
.lineStyle(StrokeStyle(lineWidth: 1.5, dash: [4, 2]))
}---
Chart Selection with Overlay Annotation
Show a tooltip at the selected position using chartOverlay:
@State private var selectedDate: Date?
var body: some View {
Chart(data) { item in
LineMark(
x: .value("Date", item.date),
y: .value("Value", item.value)
)
if let selectedDate,
let match = data.first(where: { Calendar.current.isDate($0.date, inSameDayAs: selectedDate) }) {
RuleMark(x: .value("Selected", match.date))
.foregroundStyle(.secondary)
PointMark(
x: .value("Date", match.date),
y: .value("Value", match.value)
)
.symbolSize(60)
.annotation(position: .top) {
Text("\(match.value, format: .number)")
.font(.caption)
.padding(4)
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 4))
}
}
}
.chartXSelection(value: $selectedDate)
}---
Scrollable Chart with Visible Domain
@State private var scrollPosition: Date?
var body: some View {
Chart(dailySteps) { item in
BarMark(
x: .value("Date", item.date, unit: .day),
y: .value("Steps", item.steps)
)
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 3600 * 24 * 7) // 7 days
.chartScrollPosition(x: $scrollPosition)
.chartScrollTargetBehavior(
.valueAligned(matching: DateComponents(hour: 0), majorAlignment: .page)
)
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { value in
AxisGridLine()
AxisValueLabel(format: .dateTime.weekday(.abbreviated))
}
}
}---
Function Plotting (LinePlot, iOS 18+)
Standard function y = f(x)
Chart {
LinePlot(x: "x", y: "y", domain: -2 * .pi ... 2 * .pi) { x in
sin(x)
}
.foregroundStyle(.blue)
}
.chartYScale(domain: -1.5...1.5)Parametric function (x, y) = f(t)
Chart {
LinePlot(x: "x", y: "y", t: "t", domain: 0 ... 2 * .pi) { t in
(x: cos(t), y: sin(t))
}
}
.chartXScale(domain: -1.5...1.5)
.chartYScale(domain: -1.5...1.5)Range area function
Chart {
AreaPlot(x: "x", yStart: "min", yEnd: "max", domain: 0...10) { x in
(yStart: sin(x) - 0.5, yEnd: sin(x) + 0.5)
}
.foregroundStyle(.blue.opacity(0.2))
}---
3D Charts and Surfaces (Chart3D, iOS 26+)
Use Chart3D when the data has a real third dimension, such as (x, y, z) points, 3D regions, or a bivariate surface. Keep ordinary category comparison, time series, and proportions in 2D charts because they are easier to label, compare, and make accessible.
SurfacePlot for bivariate functions
@State private var pose: Chart3DPose = .default
Chart3D {
SurfacePlot(x: "x", y: "y", z: "z") { x, z in
sin(2 * x) * cos(2 * z)
}
.foregroundStyle(.heightBased)
}
.chartXScale(domain: -2...2)
.chartYScale(domain: -1...1)
.chartZScale(domain: -2...2)
.chart3DPose($pose)3D point cloud
Chart3D(points) { point in
PointMark(
x: .value("Width", point.x),
y: .value("Height", point.y),
z: .value("Depth", point.z)
)
.foregroundStyle(by: .value("Cluster", point.cluster))
}
.chart3DCameraProjection(.perspective)3D review notes
- Confirm the z dimension is meaningful and labeled; do not use depth only for decoration.
- Set explicit x/y/z domains when users need stable comparisons across states.
- Bind
Chart3DPosewhen users need to inspect the scene interactively. - Use
SurfacePlotfory = f(x, z)surfaces; use 3D mark initializers for observed data points or regions.
---
Accessibility
Automatic VoiceOver support
Swift Charts provides automatic VoiceOver descriptions for chart elements. The framework reads axis labels and values to visually impaired users without additional code. Ensure .value("Label", ...) strings are descriptive.
Custom accessibility labels
Chart(data) { item in
BarMark(
x: .value("Month", item.month),
y: .value("Sales", item.sales)
)
.accessibilityLabel("Sales for \(item.month)")
.accessibilityValue("\(item.sales) units sold")
}Accessibility on vectorized plots (KeyPath-based)
BarPlot(data, x: .value("Month", \.month), y: .value("Sales", \.sales))
.accessibilityLabel(\.accessibilityDescription)
.accessibilityValue(\.formattedSales)Audio graphs
The system automatically generates audio representations of chart data for VoiceOver users. Use clear, consistent data labels to ensure audio graphs convey meaningful patterns.
Best practices
- Use descriptive strings in
.value("Label", ...)-- these become VoiceOver labels. - Add
.accessibilityLabeland.accessibilityValuefor context beyond raw numbers. - Test with VoiceOver enabled: navigate the chart and verify each element is announced.
- Avoid
.accessibilityHidden(true)on data-bearing marks.
---
Dynamic Type and Color Considerations
Dynamic Type
Charts automatically adjust axis label sizes with Dynamic Type. Avoid fixed frame heights that clip labels at larger text sizes.
// WRONG -- clips at large text sizes
Chart(data) { ... }
.frame(height: 200)
// CORRECT -- adaptive height
Chart(data) { ... }
.frame(minHeight: 200)
.frame(maxHeight: 400)Test charts at the "Accessibility Extra Extra Extra Large" text size to verify axis labels, annotations, and legends remain readable.
Color
- Avoid encoding meaning solely in color. Pair
.foregroundStyle(by:)with
.symbol(by:) or .lineStyle(by:) for distinguishability.
- Use system colors that adapt to both light and dark modes.
- Test with color blindness simulations in the Accessibility Inspector.
LineMark(x: .value("Date", item.date), y: .value("Value", item.value))
.foregroundStyle(by: .value("Category", item.category))
.symbol(by: .value("Category", item.category))
.lineStyle(by: .value("Category", item.category))---
Performance: Vectorized Plots for Large Datasets
For datasets exceeding 1000 data points, use vectorized plot types instead of individual marks. Vectorized plots accept entire collections and render efficiently.
When to use vectorized plots
| Data Points | Recommended Approach |
|---|---|
| < 100 | Individual marks (BarMark, LineMark, etc.) |
| 100 - 1000 | Either approach; profile if performance matters |
| > 1000 | Vectorized plots (BarPlot, LinePlot, etc.) |
Data-driven vectorized plot
struct SensorReading: Identifiable {
let id: Int
let timestamp: Date
let temperature: Double
var color: Color { temperature > 30 ? .red : .blue }
var accessibilityDescription: Text {
Text("\(timestamp.formatted(.dateTime.hour().minute())): \(temperature, specifier: "%.1f") degrees")
}
}
Chart {
LinePlot(
readings,
x: .value("Time", \.timestamp),
y: .value("Temperature", \.temperature)
)
.foregroundStyle(.blue)
}KeyPath modifier ordering
Apply KeyPath-based modifiers before simple-value modifiers:
// WRONG
BarPlot(data, x: .value("X", \.x), y: .value("Y", \.y))
.opacity(0.8) // value modifier
.foregroundStyle(\.color) // KeyPath -- compiler error
// CORRECT
BarPlot(data, x: .value("X", \.x), y: .value("Y", \.y))
.foregroundStyle(\.color) // KeyPath first
.opacity(0.8) // value modifier secondAvailable vectorized plot types
| Plot Type | Mark Equivalent | Available From |
|---|---|---|
BarPlot | BarMark | iOS 18+ |
LinePlot | LineMark | iOS 18+ |
PointPlot | PointMark | iOS 18+ |
AreaPlot | AreaMark | iOS 18+ |
RulePlot | RuleMark | iOS 18+ |
RectanglePlot | RectangleMark | iOS 18+ |
SectorPlot | SectorMark | iOS 18+ |
---
Dark Mode and Theming
Automatic adaptation
Swift Charts inherits the current color scheme automatically. System colors (.blue, .orange, .green) adapt to light and dark modes without extra code.
Custom color palettes
Use .chartForegroundStyleScale to define a consistent palette:
Chart(data) { item in
BarMark(
x: .value("Category", item.category),
y: .value("Value", item.value)
)
.foregroundStyle(by: .value("Category", item.category))
}
.chartForegroundStyleScale([
"Electronics": .blue,
"Clothing": .purple,
"Food": .orange,
"Books": .green,
"Other": .gray
])Background and plot area styling
Chart(data) { ... }
.chartPlotStyle { plotArea in
plotArea
.background(.quaternary.opacity(0.3))
.border(.quaternary, width: 0.5)
}Axis styling
.chartXAxisStyle { axis in
axis.background(.blue.opacity(0.05))
}Testing dark mode
Always preview charts in both light and dark color schemes. In Xcode previews:
#Preview {
ChartView()
.preferredColorScheme(.dark)
}Verify:
- Axis labels and grid lines are readable.
- Data colors maintain sufficient contrast.
- Annotations and legend text adapt properly.
---
Heat Map Pattern
Chart(heatMapData) { item in
RectangleMark(
x: .value("Hour", item.hour),
y: .value("Day", item.day)
)
.foregroundStyle(by: .value("Count", item.count))
}
.chartForegroundStyleScale(range: Gradient(colors: [.blue, .yellow, .red]))---
Stacking Methods
| Method | Behavior |
|---|---|
.standard | Default. Regions stack on top showing absolute values. |
.normalized | Scales to 0-100% proportional view. |
.center | Baseline centered (streamgraph). |
.unstacked | Overlapping; no stacking. |
AreaMark(
x: .value("Date", item.date),
y: .value("Revenue", item.revenue),
stacking: .normalized
)
.foregroundStyle(by: .value("Category", item.category))---
MarkDimension Options
| Dimension | Description |
|---|---|
.automatic | Framework decides |
.fixed(CGFloat) | Exact pixel size |
.inset(CGFloat) | Inset from available space |
.ratio(CGFloat) | Proportion of available space (0...1) |
Use for width, height on BarMark and innerRadius, outerRadius on SectorMark.
---
Symbol Configuration
Built-in shapes
circle, square, triangle, diamond, pentagon, plus, cross, asterisk
PointMark(x: .value("X", item.x), y: .value("Y", item.y))
.symbol(.diamond)
.symbolSize(80)Data-driven symbol encoding
PointMark(x: .value("X", item.x), y: .value("Y", item.y))
.symbol(by: .value("Category", item.category))Custom symbol view
PointMark(x: .value("X", item.x), y: .value("Y", item.y))
.symbol {
Image(systemName: "star.fill")
.font(.caption2)
}---
ChartProxy and Coordinate Conversion
Use chartOverlay or chartBackground to access ChartProxy:
.chartOverlay { proxy in
GeometryReader { geometry in
Rectangle()
.fill(.clear)
.contentShape(Rectangle())
.gesture(
DragGesture()
.onChanged { value in
let origin = geometry[proxy.plotAreaFrame].origin
let location = CGPoint(
x: value.location.x - origin.x,
y: value.location.y - origin.y
)
if let date: Date = proxy.value(atX: location.x) {
selectedDate = date
}
}
)
}
}Key ChartProxy methods
| Method | Purpose |
|---|---|
position(forX:) | Data value to screen x-coordinate |
position(forY:) | Data value to screen y-coordinate |
value(atX:as:) | Screen x-coordinate to data value |
value(atY:as:) | Screen y-coordinate to data value |
plotAreaSize | Size of the plot area |
plotAreaFrame | Anchor for the plot area frame |
---
Quick Reference: Chart View Modifiers
Axes
chartXAxis(_:)/chartXAxis(content:)chartYAxis(_:)/chartYAxis(content:)chartXAxisLabel(...)/chartYAxisLabel(...)chartXAxisStyle(content:)/chartYAxisStyle(content:)
Scales
chartXScale(domain:range:type:)and variantschartYScale(domain:range:type:)and variantschartZScale(domain:range:type:)forChart3DchartForegroundStyleScale(_:)-- custom color mapping
3D charts (iOS 26+)
Chart3DwithSurfacePlotor 3D mark initializerschart3DPose(_:)for interactive pose bindingchart3DCameraProjection(_:)for orthographic/perspective projection
Legend
chartLegend(_:)-- visibilitychartLegend(position:alignment:spacing:)-- positioningchartLegend(position:alignment:spacing:content:)-- custom content
Selection (iOS 17+)
chartXSelection(value:)/chartXSelection(range:)chartYSelection(value:)/chartYSelection(range:)chartAngleSelection(value:)-- forSectorMark
Scrolling (iOS 17+)
chartScrollableAxes(_:)chartXVisibleDomain(length:)/chartYVisibleDomain(length:)chartScrollPosition(initialX:)/chartScrollPosition(x:)chartScrollTargetBehavior(_:)
Overlay and Background
chartOverlay(alignment:content:)-- withChartProxychartBackground(alignment:content:)-- withChartProxychartPlotStyle(content:)-- plot area styling
---
Apple Documentation Links
Related skills
How it compares
Pick swift-charts over generic SwiftUI skills when the task is specifically Apple Charts marks, vectorized plots, or Chart3D—not custom Canvas drawing.
FAQ
When use vectorized plots?
For one thousand plus 2D points use BarPlot, LinePlot, or related vectorized plots.
How enable horizontal scroll on dense data?
Use chartScrollableAxes with chartXVisibleDomain and chartScrollPosition.
When use Chart3D?
Use Chart3D only for real spatial or surface data, not flat 2D series.
Is Swift Charts safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.