Search code examples
swiftgraphchartsswiftui-charts

Extra Line in Swift Chart


I am trying to get the new Swift Charts to work, but there is a funny line running from the first to last point in the chart which I cannot resolve.

Here is the code:


    var ChartView: some View {
            HStack   {
                //Anx_6
                Chart(genRtrv.TUHist_Chart) { series in
                    
                    ForEach(genRtrv.TUHist_Chart.reversed(), id: \.Timestamp) { data in
                        let vdate = data.Timestamp
                        let minus_3m = Calendar.current.date(byAdding: .month, value: -3, to:     Date())!
                        let minus_6m = Calendar.current.date(byAdding: .month, value: -6, to: Date())!
                        
                        if vdate > minus_3m {
                            LineMark(
                                x: .value("Date", data.Timestamp, unit: .day),
                                y: .value("Thumbs Up", data.TU)
                            )
                            PointMark(
                                x: .value("Date", data.Timestamp, unit: .day),
                                y: .value("Thumbs Up", data.TU)
                            )
                        }
                    }
                }
            }
        }

Data: Start Enum of TuChart

Charted Val: 5 - Time: 2023-01-11 13:32:55 +0000
Charted Val: 5 - Time: 2023-01-11 22:20:37 +0000
Charted Val: 4 - Time: 2023-01-26 22:17:50 +0000
Charted Val: 3 - Time: 2023-02-04 22:20:36 +0000
Charted Val: 4 - Time: 2023-02-10 22:19:16 +0000
Charted Val: 3 - Time: 2023-02-21 22:19:19 +0000
Charted Val: 4 - Time: 2023-03-04 22:18:27 +0000
Charted Val: 5 - Time: 2023-03-11 03:50:51 +0000
Charted Val: 4 - Time: 2023-03-17 15:51:19 +0000
Charted Val: 3 - Time: 2023-03-23 13:54:39 +0000
Charted Val: 3 - Time: 2023-04-11 12:32:55 +0000

Result are below

(https://i.sstatic.net/YaAxK.png)

I looked on line at Apple's documentation and stackoverflow. I would just like the chart to not have the recursive line running across it.


Solution

  • The problem is that you are passing in the data and looping over it two times, first by using a Chart initialiser that takes the data as an argument

    Chart(genRtrv.TUHist_Chart) { series in
        // rest of code
    }
    

    and secondly when using a ForEach loop

    ForEach(genRtrv.TUHist_Chart.reversed(), id: \.Timestamp) { data in
         // ...
    }
    

    The most straightforward solution here is to change the Chart initialiser by instead doing

    Chart {
        // rest of code
    }