Rohit
Rohit

Reputation: 2326

Show Dyanmic Multiple Lines on Chart in Swift

I am working on app in which I have to show the json data on charts which is a swift framework I am using. I am able to show the data correctly on the charts but can't able to make the function dynamic. So that any n numbers of charts I can show on the LineChart graph.This is the library I am using https://github.com/danielgindi/Charts . This is the function I am using to show the datas on graph

func newLineChartValue(carbonLineChartValue: [LineChartValue]) {
    
    for value in self.carbonLineChartValue {
        self.zoneNames.append(value.Zone_name!)
        self.allValueArray.append(value.value_array!)
        self.colors.append(value.zone_color!)
    }
    
    var lineChartEntry1 = [ChartDataEntry]()
    var lineChartEntry2 = [ChartDataEntry]()
    var lineChartEntry3 = [ChartDataEntry]()

            
    let firstLineArray = allValueArray[0]
    print("FirstLine Data: \(firstLineArray)")
    var timeLbl = [String]()
    
    var valueOne = [Double]()
    
    for lbl in firstLineArray {
        timeLbl.append(lbl.label!)
        valueOne.append(lbl.value!)
        print("Time1:-> \(timeLbl)")
        print("Value1:-> \(valueOne)")
    }

    for i in 0..<timeLbl.count {
        lineChartEntry1.append(ChartDataEntry(x: Double(i), y: Double(valueOne[i])))
    }
    
    let set1 = LineChartDataSet(entries: lineChartEntry1, label: "")
    set1.axisDependency = .left
    set1.mode = .cubicBezier
    set1.setColor(UIColor.init(hex: colors[0]))
    set1.fillColor = UIColor.init(hex: colors[0])
    set1.setCircleColor(UIColor.init(hex: colors[0]))

    set1.lineWidth = 4
    set1.circleRadius = 4
    set1.fillAlpha = 65/255
    set1.drawCircleHoleEnabled = false
    
    
    let secondLineArray = allValueArray[1]
    var valueTwo = [Double]()
    for value in secondLineArray {
        valueTwo.append(value.value!)
        print("Value2:-> \(valueTwo)")
    }
    for i in 0..<valueTwo.count {
        lineChartEntry2.append(ChartDataEntry(x: Double(i), y: Double(valueTwo[i])))
    }
    let set2 = LineChartDataSet(entries: lineChartEntry2, label: "")
    set2.mode = .cubicBezier

    set2.axisDependency = .left
    set2.setColor(UIColor.init(hex: colors[1]))
    set2.fillColor = UIColor.init(hex: colors[1])
    set2.setCircleColor(UIColor.init(hex: colors[1]))
    set2.lineWidth = 4
    set2.circleRadius = 4
    set2.fillAlpha = 65/255
    set2.drawCircleHoleEnabled = false

    let thirdLine = allValueArray[2]
    var valueThree = [Double]()

    for value in thirdLine {
        valueThree.append(value.value!)
        print("Value3:-> \(valueThree)")
    }
    for i in 0..<valueThree.count {
        lineChartEntry3.append(ChartDataEntry(x: Double(i), y: Double(valueThree[i])))
    }
    let line3 = LineChartDataSet(entries: lineChartEntry3, label: "")
    line3.axisDependency = .left
    line3.mode = .cubicBezier
    line3.setColor(UIColor.init(hex: colors[2]))
    line3.fillColor = UIColor.init(hex: colors[2])
    line3.setCircleColor(UIColor.init(hex: colors[2]))

    line3.lineWidth = 4
    line3.circleRadius = 4
    line3.fillAlpha = 65/255
    line3.drawCircleHoleEnabled = false


    
    let lineChartData = LineChartData(dataSets: [set1,set2,line3])
    lineChartData.setDrawValues(false)
    lineChartView.xAxis.labelPosition = .bottom
    self.lineChartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
        return timeLbl[Int(index)]
    })
    self.lineChartView.data = lineChartData
    
}

This is the Struct for LineChartValue

struct LineChartValue: Codable {
var Zone_name: String?
var zone_color: String?
var value_array: [LineChartValueArray]?
}

JSON Coming from Server

{        
            "show_Zone": true
            "Zone_name": "Zone Sales",
            "zone_color": "#c69f49",
            "value_array": [
                {
                    "label": "01:00 AM",
                    "value": 0
                },
                {
                    "label": "02:00 AM",
                    "value": 0
                },
                {
                    "label": "03:00 AM",
                    "value": 0
                },
                {
                    "label": "04:00 AM",
                    "value": 0
                },
                {
                    "label": "05:00 AM",
                    "value": 0
                },
                {
                    "label": "06:00 AM",
                    "value": 0
                },
                {
                    "label": "07:00 AM",
                    "value": 0
                },
                {
                    "label": "08:00 AM",
                    "value": 0
                },
                {
                    "label": "09:00 AM",
                    "value": 0
                },
                {
                    "label": "10:00 AM",
                    "value": 0
                },
                {
                    "label": "11:00 AM",
                    "value": 0
                },
                {
                    "label": "12:00 AM",
                    "value": 0
                },
                {
                    "label": "01:00 PM",
                    "value": 0
                },
                {
                    "label": "02:00 PM",
                    "value": 0
                },
                {
                    "label": "03:00 PM",
                    "value": 0
                },
                {
                    "label": "04:00 PM",
                    "value": 0
                },
                {
                    "label": "05:00 PM",
                    "value": 0
                },
                {
                    "label": "06:00 PM",
                    "value": 0
                },
                {
                    "label": "07:00 PM",
                    "value": 0
                },
                {
                    "label": "08:00 PM",
                    "value": 0
                },
                {
                    "label": "09:00 PM",
                    "value": 0
                },
                {
                    "label": "10:00 PM",
                    "value": 0
                },
                {
                    "label": "11:00 PM",
                    "value": 0
                },
                {
                    "label": "12:00 PM",
                    "value": 0
                }
            ]
        },

I want to make this function dynamic so I can show n numbers of lines on graph.

enter image description here

Upvotes: 0

Views: 465

Answers (1)

HangarRash
HangarRash

Reputation: 15050

Here is your code reduced to use a loop over carbonLineChartValue instead of hardcoding accessing the first 3 elements of the array.

The first iteration of the array populates the timeLbl array to replicate you populating that array from the first element.

I've also removed all uses of ! to avoid possible crashes from force-unwrapping nil values.

Since I do not have your charts library nor several other structures referenced in your code I am not able to verify that this code will compile as written. There may be a mistake or two here from trying to translate your original code. But the general idea should be valid.

I also don't show the initial for loop where you populate self.zoneNames, self.allValueArray, and self.colors since it's not needed for this function. Put it back in if you need those results for other uses.

func newLineChartValue(carbonLineChartValue: [LineChartValue]) {
    var dataSets = [LineChartDataSet]()
    var timeLbl = [String]()

    for (index, chartValue) in carbonLineChartValue.enumerated() {
        guard let zoneName = chartValue.Zone_name, let zoneColor = chartValue.zone_color, let lineArray = chartValue.value_array else { continue }

        // Skip this one if it's not to be shown
        if chartValue.show_Zone == false { continue }

        let lineChartEntry = [ChartDataEntry]()
        if index == 0 {
            timeLbl = lineArray.compactMap { $0.label }
        }

        for (index, value) in lineArray.enumerated() {
            if let y = value.value {
                lineChartEntry.append(ChartDataEntry(x: Double(index), y: y))
            }
        }

        let set = LineChartDataSet(entries: lineChartEntry, label: "")
        set.mode = .cubicBezier

        set.axisDependency = .left
        set.setColor(UIColor(hex: zoneColor))
        set.fillColor = UIColor(hex: zoneColor)
        set.setCircleColor(UIColor(hex: zoneColor))
        set.lineWidth = 4
        set.circleRadius = 4
        set.fillAlpha = 65/255
        set.drawCircleHoleEnabled = false

        dataSets.append(set)
    }

    let lineChartData = LineChartData(dataSets: dataSets)
    lineChartData.setDrawValues(false)
    lineChartView.xAxis.labelPosition = .bottom
    self.lineChartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
        return timeLbl[Int(index)]
    })
    self.lineChartView.data = lineChartData
}

Upvotes: 1

Related Questions