Home > Enterprise >  How can I plot a function using SwiftUI Charts?
How can I plot a function using SwiftUI Charts?

Time:11-26

I want to plot the function y = ((4000 (120*x))*1.6)/x using SwiftUI Charts. Lets say I want to plot the function from x=1 to x=1000. I could start with making a var x = 1 and then use a for loop: for 1...1000 calculate y, add the result to the var containing all the data for the graph, add 1 to x and repeat the loop. Then I can plot the graph using SwiftUI Charts LineMark. The problem is that I don't know how to actually do this. I know how programming works because I learned it with scratch when I was younger but I don't understand Swift good enough to program this yet.

Another problem I have is that the numbers are variables from another view. I have a view named SliderView where I make the variables and you can change them with sliders and I have a view named ChartView where I want to calculate and display the graph. How can I use the variables from SliderView in ChartView and update/refresh the chart when the numbers from the vars change?

This is how I currently declare the vars in SliderView:

@State var startingPrice: Double = 4000
@State var manufacturingPrice: Double = 120
@State var profitMargin: Double = 1.6

I have tried to search on the internet for answers but SwiftUI Charts are relatively new I think and I can't find any tutorial on how to plot functions with it.

CodePudding user response:

You can put all the variables together in a model and create a computed property.

struct FunctionPlotModel{
    var startingPrice: Double = 4000
    var manufacturingPrice: Double = 120
    var profitMargin: Double = 1.6
    
    var startPoint: Int = 1
    var endPoint: Int = 1000
    
    /// Values created by formula
    var values: [(x: Double, y: Double)]{
        (startPoint...endPoint).map { x in
            let y: Double = (Double(startingPrice   Double(manufacturingPrice * Double(x)) * profitMargin) / Double(x))
            return (Double(x), y)
        }
    }
}

Then just plot and use the variables as needed

import SwiftUI
import Charts

@available(iOS 16.0, *)
struct FunctionPlotView: View {
    @State var model: FunctionPlotModel = .init()
    var body: some View {
        VStack{
            Slider(value: $model.startingPrice, in: 100...10000)
            Slider(value: $model.manufacturingPrice, in: 100...200)
            Slider(value: $model.profitMargin, in: 0.5...5)
            
            Chart {
                ForEach(model.values, id:\.x){ val in
                    LineMark(x: .value("x", val.x), y: .value("y", val.y))
                }
            }.padding()
        }
    }
}
@available(iOS 16.0, *)
struct FunctionPlotView_Previews: PreviewProvider {
    static var previews: some View {
        FunctionPlotView()
    }
}
  • Related