Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating line chart with multiple lines

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.

like image 362
John Harrington Avatar asked Nov 21 '25 21:11

John Harrington


2 Answers

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)
}
like image 102
workingdog support Ukraine Avatar answered Nov 24 '25 19:11

workingdog support Ukraine


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.

like image 39
Marcy Avatar answered Nov 24 '25 21:11

Marcy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!