2

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)
            )
        }
    }
}

2 Answers 2

4

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])
            )
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

What does the nr represent?
It is counting array elements.
This is a cleaner approach than the other answer. Thank you for posting this.
3

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)
        )
    }
}

1 Comment

That works. Thank you for the help. You could also use $0 and $1 for the x and y values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.