Search code examples
swiftswiftuiswiftui-charts

How to limit the Y values when using a function plot like LinePlot in SwiftUI Charts?


The new SwiftUI function-plot charts for Swift 6 does not limit the y values. So those values can go off the Chart and cover other UI elements on the screen.

The following is an example of the problem. The area in green is the chart area that the values should be contained in. However, the blue lines run off the screen.:

enter image description here

This is the chart's code which is based on one of Apple's WWDC examples:


import SwiftUI
import Charts

struct ChartView: View {
    var body: some View {
        Chart {
            LinePlot(x: "x", y: "1 / x", domain: -10...10) { x in
                guard x != 0 else {
                    return .nan
                }
                return 1 / x
            }
        }
        .chartBackground(alignment: .center) { _ in
            Rectangle()
                .fill(Color.green)
        }
        .frame(width: 300, height: 300)
        .chartXScale(domain: -10...10)
        .chartYScale(domain: -10...10)
    }
}

The notes in the Feedback Assistant release regarding Swift Charts say the following. enter image description here

But I don't know how to set the domain for y on the function or if this is referring to the same problem. For the workaround, I used the LinePlot's domain parameter but it didn't seem to have an effect on x or y. If the domain parameter is removed everything is the same.

How can this chart be fixed OR how can the workaround be implemented?


Solution

  • It seems like the plot is not clipped at the frame of the Chart. You can do that manually with clipped().

    Chart {
        // ...
    }
    .chartBackground(alignment: .center) { _ in
        Rectangle()
            .fill(Color.green)
    }
    .frame(width: 300, height: 300)
    .clipped() // <-----