swiftuichartsios16

Fixed range for y-axis in Swift Charts


I want that my y-axis always shows a range from 0-60 even though there are data sets that do not represent the full range. E.g. if I'm showing a data set with values of just 10 and 40 the y-axis range is only from 0-40 instead of 0-60.

Any ideas how to configure the y-axis for Swift Charts (iOS 16) with a fixed range?

Chart { 
        ForEach(model.series.entries, id: \.weekday) { element in
            BarMark(
                x: .value("Day", element.weekday, unit: .day),
                y: .value("Feeling", element.value)
            )
        }
    }
    .chartXAxis {
        let unit: Calendar.Component = model.resolution == .yearly ? .month : .day
        
        AxisMarks(values: .stride(by: unit, count: 1)) { _ in
            AxisGridLine()
            AxisValueLabel(format: .dateTime.weekday(.narrow), centered: true)
        }
    }

Content with values of 40 and 50

Content with values of 10 and 40


Solution

  • try adding this to your Chart, ...to configure the y-axis for Swift Charts (iOS 16) with a fixed range:

    .chartYScale(domain: 0...60)