In Swift Charts, how do you plot a week of daily step counts from an array of structs as a bar chart?
answer
- a view built from marks
- Chart behaves like ForEach
- Identifiable or an id key path
- .value(label, value) per axis
- unit: .day for a Date
basics
~20 sPass the array to Chart and return one BarMark per element, giving x and y as PlottableValues built with .value("Day", entry.day, unit: .day) and .value("Steps", entry.steps); the elements must be Identifiable or you supply id:.
solid answer
~40 sA `Chart` is a SwiftUI view whose content is marks. `Chart(week) { entry in BarMark(x: .value("Day", entry.day, unit: .day), y: .value("Steps", entry.steps)) }` creates one bar per element, much as `ForEach` creates one view per element, so the element type must be `Identifiable` or you call `Chart(week, id: \.day)`. Each `.value(_:_:)` builds a `PlottableValue`: a label naming the dimension plus a value whose type conforms to `Plottable`. The value's type decides the scale: `String` gives categories, `Int` or `Double` a quantity, `Date` a time axis. For a `Date`, `unit: .day` treats each value as a whole day, so each bar fills its day's slot. When you need marks that do not repeat per element, such as a goal line, write `Chart { ForEach(week) { ... }; RuleMark(...) }` instead.
code
swift · 23 linesimport SwiftUI
import Charts
struct DailySteps: Identifiable {
let id = UUID()
let day: Date
let steps: Int
}
struct WeeklyStepsChart: View {
let week: [DailySteps]
var body: some View {
Chart(week) { entry in
BarMark(
x: .value("Day", entry.day, unit: .day),
y: .value("Steps", entry.steps)
)
}
.chartYAxisLabel("Steps")
.frame(height: 220)
}
}go deeper
Recall the shape: Chart over the array, one BarMark per element, x and y as .value(label, value). Know that elements must be Identifiable or given an id key path.
Explain what PlottableValue carries, how the Swift type of the value picks a categorical, numeric or date scale, and why unit: .day matters for daily totals.
Show you can spot data bugs that surface as chart bugs, such as duplicate days stacking silently, and choose between the data initializer and a builder with ForEach.
Frame Swift Charts as the default for in-app charts on iOS 16 and later, and know when a chart's data model deserves its own aggregation layer before plotting.
## What a chart is made of Swift Charts is Apple's declarative charting framework, shipped with **iOS 16**. A `Chart` is an ordinary SwiftUI view, so it sits in a `VStack`, takes `.frame(height:)` and re-renders when its data changes. What it draws is described by **marks**: `BarMark`, `LineMark`, `AreaMark`, `PointMark`, `RuleMark` and `RectangleMark` from the first release, and `SectorMark` from iOS 17. Each mark maps properties of one data element to visual channels such as x position, y position and colour. A bar chart of a week of steps therefore needs three things: - a data type, for example `struct DailySteps { let day: Date; let steps: Int }`; - a `Chart` that walks the array; - one `BarMark` per element, saying which property goes on x and which on y. ## Feeding data: `Chart(data)` versus `Chart { ForEach }` `Chart` has three initializers. `Chart(_:content:)` takes a `RandomAccessCollection` whose elements are `Identifiable` and calls the closure once per element. Apple's documentation describes it as behaving "a lot like a SwiftUI ForEach", and its declaration builds exactly that: the content type is a `ForEach`. `Chart(_:id:content:)` does the same for elements that are not `Identifiable`, taking a key path such as `\.day`. Pass a non-`Identifiable` array to the first form and the compiler stops with "initializer 'init(_:content:)' requires that 'DailySteps' conform to 'Identifiable'". The third form, `Chart(content:)`, takes a builder and no data. Inside it you write your own `ForEach` loops plus any marks that should appear once: ```swift Chart { ForEach(week) { entry in BarMark(x: .value("Day", entry.day, unit: .day), y: .value("Steps", entry.steps)) } RuleMark(y: .value("Goal", 10_000)) } ``` Use the data form when every mark comes from the same collection, and the builder form when you combine several collections or add constant marks. ## `PlottableValue` and the `.value(_:_:)` labels Every mark parameter (`x:`, `y:`, `angle:`, `series:`) and every encoding modifier (`foregroundStyle(by:)`, `symbol(by:)`) takes a `PlottableValue`. You build one with the static `.value(_:_:)` method: the first argument is a **label** (a `LocalizedStringKey`, a `String`, a `Text` or a `LocalizedStringResource`), the second the **value**. The label names the data dimension. Swift Charts uses it when it describes that dimension, and per mark you can override what VoiceOver reads with `accessibilityLabel(_:)` and `accessibilityValue(_:)`. Visible axis titles are a separate matter: add them with `chartXAxisLabel(_:)` and `chartYAxisLabel(_:)`. The value must conform to `Plottable`. The type you pass decides what kind of scale Charts builds: | Value type | Kind of data | Typical axis | |---|---|---| | `String` | categorical | one slot per distinct value | | `Int`, `Double` | quantitative | a numeric range | | `Date` | temporal | a time axis | | an enum with a `String` raw value that adopts `Plottable` | categorical | the raw values, used as localized keys | A custom type can adopt `Plottable` by mapping itself to one of the primitive plottable types through `primitivePlottable` and `init?(primitivePlottable:)`. ## Dates and the `unit` parameter A step total belongs to a whole day, not to the instant stored in the `Date`. The overload `.value(_:_:unit:calendar:)` says so: `.value("Day", entry.day, unit: .day)` treats each date as the interval of its day, so a bar fills that day's slot on the time axis. Pass `.hour`, `.weekOfYear` or `.month` for other bin sizes. ## When several bars land on the same x If two elements map to the same location, `BarMark` stacks them; the documentation states this outright. With one entry per day you get one bar per day. If the array accidentally holds two rows for Monday, Monday's bar is the sum of both, drawn as one column in one colour. That is a data bug that looks like a chart bug. ## Same data, other marks Because the encoding lives in the `.value` arguments, the mark type decides how the same week is drawn, and swapping it is a one-word change: - `BarMark(x:y:)` draws one bar per element; - `LineMark(x:y:)` joins the days into a line; - `PointMark(x:y:)` draws one symbol per day; - `AreaMark(x:y:)` fills the region under the line. Marks compose inside one chart, so a `LineMark` and a `PointMark` over the same values give a line with a dot on each day. Orientation follows the value types as well: put the step count on `x` and a `String` day name on `y`, and `BarMark` draws horizontal bars. Which form suits the data is a visualization-design decision; the API point is that the mark, not a chart-type setting, decides the drawing. ## Common mistakes 1. Passing a non-`Identifiable` array to `Chart(_:content:)` instead of adding `id:` or adopting `Identifiable`. 2. Plotting a `Date` without `unit:` when each value represents a whole day. 3. Converting dates to `String` to "fix" the axis, which turns time into plain categories and drops the time scale. 4. Expecting `.value`'s label to appear as an axis title without `chartYAxisLabel(_:)`. 5. Putting a one-off mark inside `Chart(week) { entry in ... }`, where it is repeated once per element.
- In Swift Charts, what happens if the step array holds two entries for the same day?`BarMark` stacks marks that map to the same location, so that day shows one column whose height is the sum of both entries. Without `foregroundStyle(by:)` both segments share one colour and the chart looks like a single tall bar, so the duplicate goes unnoticed. Aggregate per day before plotting, or encode the second dimension with `foregroundStyle(by:)` when the split is intended.
- In Swift Charts, how do you plot an enum such as an activity kind as a category?Give the enum a `String` raw value and declare conformance to `Plottable`; Swift Charts provides the implementation for `String`-backed raw-representable types. The raw values are then used as localized string keys wherever the chart shows the category as text, for example on an axis.
- Swift Charts needs a third-party package to draw a bar chart
- Chart(data) works with any array, Identifiable or not
- Converting dates to strings is the right way to get a day axis
- The .value label automatically becomes the visible axis title
- BarMark draws two bars side by side when they share an x value