skip to content

In Swift Charts, what does foregroundStyle(by:) do that foregroundStyle(_:) does not, for steps split into walking and running?

level: middleimportance: should knowfreq 45%

answer

  1. data-driven versus fixed style
  2. a scale maps values to colours
  3. a legend comes with it
  4. same x location stacks
  5. chartForegroundStyleScale pins colours

basics

~10 s

foregroundStyle(by:) maps a data value to a colour through a scale, so each activity gets its own style, a legend appears and LineMarks split into series; foregroundStyle(_:) paints every mark one fixed ShapeStyle.

solid answer

~40 s

`foregroundStyle(_:)` takes a `ShapeStyle` and paints every mark it is applied to the same way. `foregroundStyle(by:)` takes a `PlottableValue`, such as `.value("Activity", entry.activity)`, and encodes that data dimension: Swift Charts builds a colour scale with one style per distinct value and adds a legend. For bars, walking and running at the same day already stack, because `BarMark` stacks marks at the same location; `by:` is what makes the two segments distinguishable. For `LineMark`, marks with the same foreground-style value are grouped into their own line, so the modifier also splits series. To fix which colour each activity gets, add `chartForegroundStyleScale(["Walking": .teal, "Running": .orange])`; to move or hide the legend, use `chartLegend`.

code

swift · 29 lines
swift
import SwiftUI
import Charts

struct ActivitySteps: Identifiable {
    let id = UUID()
    let day: Date
    let activity: String   // "Walking" or "Running"
    let steps: Int
}

struct StepsByActivityChart: View {
    let entries: [ActivitySteps]

    var body: some View {
        Chart(entries) { entry in
            BarMark(
                x: .value("Day", entry.day, unit: .day),
                y: .value("Steps", entry.steps)
            )
            .foregroundStyle(by: .value("Activity", entry.activity))
            // .position(by: .value("Activity", entry.activity)) puts the bars side by side
        }
        .chartForegroundStyleScale([
            "Walking": Color.teal,
            "Running": Color.orange
        ])
        .chartLegend(position: .bottom)
    }
}

go deeper

for a junior

Recall that foregroundStyle(by:) takes a .value and colours by data, while foregroundStyle(_:) takes a colour, and that the first one gives you a legend.

for a middle

Explain the scale behind the encoding, why same-x bars stack, how stacking: and position(by:) change that, and how LineMark groups series by style.

for a senior

Pin category colours with chartForegroundStyleScale so screens agree, and diagnose a merged line or a silently stacked bar from the code alone.

for a principal

Treat category-to-colour mappings as shared app vocabulary, defined once and reused by every chart, rather than chosen per screen.

## Two modifiers, two jobs Swift Charts offers two foreground-style modifiers on chart content, and they answer different questions. | Modifier | Argument | What it means | |---|---|---| | `foregroundStyle(_:)` | a `ShapeStyle` such as `.orange` or a gradient | paint these marks this way | | `foregroundStyle(by:)` | a `PlottableValue` such as `.value("Activity", entry.activity)` | colour encodes this data dimension | The first is decoration: every mark it touches looks the same, and the chart has no idea why. The second is an **encoding**, in the same sense that `x:` and `y:` are encodings: a data value is mapped through a scale to a visual value. Here the visual value is a colour instead of a position. ## What `foregroundStyle(by:)` sets in motion When you write `.foregroundStyle(by: .value("Activity", entry.activity))`, several things follow from the one modifier: - **A colour scale.** Each distinct value ("Walking", "Running") gets a style from the default palette. The documentation notes that colours repeat once there are more series than palette colours. - **A legend.** The chart adds a legend that tells the reader which colour means which value. A fixed `foregroundStyle(_:)` carries no data value, so there is nothing for a legend to explain. - **Series for lines.** For `LineMark`, Apple's documentation says that when `series:` is unspecified, marks with the same foreground-style value are grouped and drawn as their own line. A heart-rate chart mixing resting and workout samples draws one zigzag through both until a `by:` encoding or `series:` separates them. ## Stacking and grouping bars For bars, the split interacts with **stacking**. `BarMark` stacks automatically when more than one bar maps to the same location, so walking and running on Monday already sit on top of each other before you add any colour; without `by:` they just look like one tall bar. The `stacking:` parameter of the `BarMark` initializer takes a `MarkStackingMethod`: | Value | Effect | |---|---| | `.standard` (the default) | segments stack from zero | | `.normalized` | each stack fills the full height, showing shares | | `.center` | stacks are centred on a baseline | | `.unstacked` | every bar starts from zero, so bars overlap | To put the activities **side by side** instead of stacked, add `position(by: .value("Activity", entry.activity))`, which offsets marks that share an x value according to the given dimension. ## Pinning colours with `chartForegroundStyleScale` Without an explicit scale the framework chooses the colours, so nothing in your code guarantees that "Running" is orange on every screen and in every week's data. `chartForegroundStyleScale` is a view modifier on the chart that fixes the mapping: ```swift .chartForegroundStyleScale([ "Walking": Color.teal, "Running": Color.orange ]) ``` It has other forms too: `chartForegroundStyleScale(domain:range:type:)` for parallel arrays, and `chartForegroundStyleScale(mapping:)` for a closure from value to style. Choosing which colours to use is a visualization-design decision; the API point is that the mapping lives on the scale, not on each mark. ## The legend `chartLegend(position:alignment:spacing:)` moves the generated legend, for example to `.bottom`; `chartLegend(position:alignment:spacing:content:)` replaces it with your own view; and `chartLegend(.hidden)` removes it when the categories are labelled some other way. ## Other channels that work the same way Colour is one of several channels that take a data value with a `by:` label, and each has a matching chart-level scale modifier: | Content modifier | Encodes the value as | Scale modifier | |---|---|---| | `foregroundStyle(by:)` | colour or other `ShapeStyle` | `chartForegroundStyleScale` | | `lineStyle(by:)` | stroke style, such as dashes | `chartLineStyleScale` | | `symbol(by:)` | point symbol shape | `chartSymbolScale` | | `symbolSize(by:)` | symbol size | `chartSymbolSizeScale` | Combining two channels for the same dimension, for example `foregroundStyle(by:)` and `symbol(by:)` on a heart-rate chart, keeps the series apart for readers who cannot rely on colour. Each encoding is driven by the same data value, so the legend can show one entry per value. ## Common mistakes 1. Writing `.foregroundStyle(.value("Activity", entry.activity))` without the `by:` label; the compiler reports a missing argument label, because the unlabelled form expects a `ShapeStyle`. 2. Colouring each `ForEach` with its own `foregroundStyle(.orange)` and then wondering why no legend appears. 3. Expecting stacked bars to separate into groups without `position(by:)`. 4. Relying on the default palette for colours that must stay stable across screens. 5. Splitting a line chart by sorting the data instead of declaring a series.

  • In Swift Charts, how do you show walking and running as two bars side by side for each day?
    Keep `foregroundStyle(by:)` for the colour and add `position(by: .value("Activity", entry.activity))` to the `BarMark`. Marks that share an x value are then offset within the day's slot according to the activity instead of stacking.
  • In Swift Charts, how do you show each activity's share of the day rather than raw counts?
    Pass `stacking: .normalized` to the `BarMark` initializer. Each day's stack then fills the full height, so segment heights show proportions, and the y-axis reads as a fraction instead of a step count.

  • foregroundStyle(.orange) on each ForEach gives you a legend
  • Bars at the same x value are drawn side by side by default
  • Colours from foregroundStyle(by:) are fixed per value across every chart
  • A LineMark chart always draws one line however you style it
  • chartLegend is what assigns colours to categories