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)
)
}
}
}
This might help
import SwiftUI
import Charts
struct ContentView: View {
let ydata = [1, 4.5, 3, 6, 7, 5.2, 9, 12.5]
var body: some View {
Chart(0..<ydata.count, id: \.self)
{ nr in
LineMark(
x: .value("X values", nr),
y: .value("Y values", ydata[nr])
)
}
}
}