21

Looking over Apple Documentation I found a straightforward way of doing this provided your dataset is structured correctly (mine is not). I've been working with a CSV file containing rows structured as below:

PM2.5 data, PM10 data, DateTime
PM2.5 data, PM10 data, DateTime
...

And I've parsed each row into a Measurement object:

struct Measurement: Identifiable {
    var id: String // time of measurement 
    var pm25: Float
    var pm10: Float
}

I naively assumed I could just add multiple line marks as so (measurements is an array of Measurement objects):

            Chart(measurements){
                LineMark (
                    x: .value("Time", $0.id),
                    y: .value("PM2.5", $0.pm25)
                )
                
                LineMark (
                    x: .value("Time", $0.id),
                    y: .value("PM2.5", $0.pm10)
                )
            }

But this does not create multiple lines. Can anyone provide any suggestions on how to achieve this using Swift Charts in Swift UI? I found many solutions on Stack Overflow but they are for Swift 4 or older, nothing for SwiftUI.

0

2 Answers 2

31

you could try this simple approach, using the series version of LineMark:

Chart(measurements) {
    LineMark(
        x: .value("Time", $0.id),
        y: .value("PM2.5", $0.pm25),
        series: .value("pm25", "A")  // <-- here
    ).foregroundStyle(.red)
    
    LineMark(
        x: .value("Time", $0.id),
        y: .value("PM1.0", $0.pm10),
        series: .value("pm10", "B")   // <-- here
    ).foregroundStyle(.green)
}
Sign up to request clarification or add additional context in comments.

Comments

3

Another approach is using .linestyle(by:) where the second string becomes a chart label and the lines are automatically given different stroke types.

    Chart(measurements){
        LineMark (
            x: .value("Time", $0.id),
            y: .value("PM2.5", $0.pm25)
        )
        .lineStyle(by: .value("Type", "PM2.5"))
        
        LineMark (
            x: .value("Time", $0.id),
            y: .value("PM2.5", $0.pm10)
        )
        .lineStyle(by: .value("Type", "PM1.0"))

The result looks like this:

enter image description here

This doesn't seem as customizable as the accepted answer. However, it's a simple solution if the default appearance is acceptable.

Comments

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.