Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

How to have different colors in Charts with AreaMark

I would like to have different fill colors in my chart. What I want to achieve is that if the values drop below 0 the fill color should be red. If they are above the fill color should be red. My code looks as follows:

import SwiftUI
import Charts

struct DataPoint: Identifiable {
    let id: UUID = UUID()
    let x: Int
    let y: Int
}

struct AlternatingChartView: View {
    
    enum Gradients {
        static let greenGradient = LinearGradient(gradient: Gradient(colors: [.green, .white]), startPoint: .top, endPoint: .bottom)
        static let blueGradient = LinearGradient(gradient: Gradient(colors: [.white, .blue]), startPoint: .top, endPoint: .bottom)
    }
    
    let data: [DataPoint] = [
        DataPoint(x: 1, y: 10),
        DataPoint(x: 2, y: -5),
        DataPoint(x: 3, y: 20),
        DataPoint(x: 4, y: -8),
        DataPoint(x: 5, y: 15),
    ]
    
    

    var body: some View {
        Chart {
            ForEach(data) { data in
                AreaMark(
                    x: .value("Data Point", data.x),
                    y: .value("amount", data.y))
                .interpolationMethod(.catmullRom)
                .foregroundStyle(data.y < 0 ? Color.red : Color.green)
                
                LineMark(
                x: .value("Data Point", data.x),
                y: .value("amount", data.y))
                .interpolationMethod(.catmullRom)
                .foregroundStyle(Color.black)
                .lineStyle(StrokeStyle.init(lineWidth: 4))
                
            }
        }
        .frame(height: 200)
    }
}

#Preview {
    AlternatingChartView()
}

The result looks like this:

I also tried using

foregroundStyle(by:)

and

chartForegroundStyleScale(_:)

but the result was, that two separate areas had been drawn. One for the below and one for the above zero datapoints.

So, what would be the right approach to have two different fill colors?

How to have different colors in Charts with AreaMark
 
 
Q