Search code examples
iosswiftios-charts

Chart View Integration issue?


I implemented Chart view from GitHub link Charts help me how to set chart data from my api?


Solution

  • after getting response from API i use this below lines of code to populate chart data

       var newData = [ChartDataEntry]()
       var month:[String] = []
       for i in 0 ..< self.graphJSON.count{
    
        if self.graphJSON[i]["savings"].null == nil{
           let saving = self.graphJSON[i]["savings"].rawString()!
            if let savingInt = Int("\(saving)"){
                newData.append(ChartDataEntry(x:Double(i),y:Double(savingInt)))
            }
         }
    
         if self.graphJSON[i]["month"].null == nil{
           month.append("\(self.graphJSON[i]["month"].rawString()!)")
         }
       }
    
    
    chartView.xAxis.labelPosition = .bottom
    chartView.rightAxis.forceLabelsEnabled = false
    
    chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:month)
    
    //Also, you probably want to add:
    chartView.xAxis.granularity = 1
    //Generate Colors
    var circleColors: [NSUIColor] = []           // arrays with circle color definitions
    for i in 0 ..< 12 {
        if i == 11 {
            let color = UIColor(red:0.84, green:0.31, blue:0.12, alpha:1.0)
            circleColors.append(color)
        }
        else{
            let color = UIColor(red:0.15, green:0.67, blue:0.60, alpha:1.0)
            circleColors.append(color)
        }
    }
    
    let data = LineChartData()
    let ds1 = LineChartDataSet(values: newData, label: "Savings in ₹")
    ds1.colors = [NSUIColor.lightGray]
    ds1.circleColors = circleColors
    data.addDataSet(ds1)
    
    let xAxis:XAxis = chartView.xAxis
    xAxis.drawAxisLineEnabled = false
    xAxis.drawGridLinesEnabled = false
    
    let leftAxis:YAxis = chartView.leftAxis
    leftAxis.drawAxisLineEnabled = false
    leftAxis.drawGridLinesEnabled = false
    
    let rightAxis:YAxis = chartView.rightAxis
    rightAxis.drawAxisLineEnabled = false
    rightAxis.drawGridLinesEnabled = false
    rightAxis.drawLabelsEnabled = false
    
    
    
    self.chartView.data = data
    self.chartView.data?.highlightEnabled = false
    self.chartView.gridBackgroundColor = UIColor.white //give color you want here
    self.chartView.chartDescription?.text = "Savings Graph"
    

    Hope this will help you