Home > Mobile >  Create a SwiftUI line graph using arrays and the Swift Charts framework
Create a SwiftUI line graph using arrays and the Swift Charts framework

Time:11-19

In a SwiftUI app, I'm trying to pass an array of Y values to the Swift Charts framework to draw a line graph. I would like to create the X values based on the length or count of the Y data. I tried the approach shown below but it doesn't work because Charts wants the data as an array of structs. Is there a way to pass arrays directly to the Charts framework?

import SwiftUI
import Charts

struct ContentView: View {
    
    let ydata = [1, 4.5, 3, 6, 7, 5.2, 9, 12.5]
    let xdata = Array(0..<ydata.count)
    let data = [xdata, ydata]

    var body: some View {
        Chart(data) {
            LineMark(
                x: .value("X values", $0),
                y: .value("Y values", $1)
            )
        }
    }
}

CodePudding user response:

You can use an array of tuples, here I am using a computed property for the data

var data: [(Int, Double)] {
    Array(zip(Array(0..<ydata.count), ydata))
}

When using a tuple we need to tell Chart what the id is so the use of data is a little different

var body: some View {
    Chart(data, id: \.0) { tuple in
        LineMark(
            x: .value("X values", tuple.0),
            y: .value("Y values", tuple.1)
        )
    }
}
  • Related