Home > Net >  Swift Charts: .chartYScale only seems to work with increments of 100?
Swift Charts: .chartYScale only seems to work with increments of 100?

Time:07-08

Given this is a heart rate chart, I'm trying to make the chart's Y max scale 210 (bpm), e.g. .chartYScale(domain: 0 ... 210) however it only seems to scale correctly if I pass in 200 or 300, anything in between doesn't work. Is this intended or a bug?

import SwiftUI
import Charts
import HealthKit

struct TestYAxisRangeChart: View {
    
    let heartRateData = [80.0, 90.0, 120.0, 150.0, 160.0, 140.0, 125.0, 110.0, 88.0]
    
    var body: some View {
        Chart {
            ForEach(heartRateData, id: \.self) { sample in
                LineMark(
                    x: .value("", heartRateData.firstIndex(of: sample)!),
                    y: .value("HR", sample))
                .foregroundStyle(Color.red)
                
            }

        }
        .chartYAxis{
            AxisMarks(position: .leading)
        }
        .frame(height: 300)
        .padding(.horizontal)
        .chartYScale(domain: 0 ... 210)
    }
    
}

struct TestYAxisRangeChart_Previews: PreviewProvider {
    static var previews: some View {
        TestYAxisRangeChart()
    }
}

CodePudding user response:

Maybe you just need this (Xcode 14b4 / iOS 16):

let yValues = stride(from: 0, to: 220, by: 10).map { $0 } // << here !!

var body: some View {
    Chart {
        ForEach(heartRateData, id: \.self) { sample in
            LineMark(
                x: .value("", heartRateData.firstIndex(of: sample)!),
                y: .value("HR", sample))
            .foregroundStyle(Color.red)
            
        }

    }
    .chartYAxis{
        AxisMarks(position: .leading, values: yValues)  // << here !!
    }

demo

  • Related