Search code examples
iosswiftxcodechartsios-charts

Error when setting up X & Y axis in iOS-Charts (Xcode 7.3.1)


I'm very new to coding, so I'm sorry if this is a basic question. I am using iOS-Charts by Daniel Gindi (the most recent version on his Github) to set up a bar graph using the following code:

    import UIKit
    import Charts

    class BarChartViewController: UIViewController {

        var barChartView: BarChartView!
        var days: [String]!

        override func viewDidLoad() {
            super.viewDidLoad()

            days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
            let tasks = [1.0, 1.0, 1.5, 2.0, 3.0, 5.0, 0.0]

            setChart(days, values: tasks)
        }

        func setChart(dataPoints: [String], values: [Double]) {

            barChartView.noDataText = "You need to provide data for the chart."

            var dataEntries: [BarChartDataEntry] = Array()
            var counter = 0.0

            for i in 0..<dataPoints.count {
                counter += 1.0
                let dataEntry = BarChartDataEntry(x: values[i], y: counter)
                dataEntries.append(dataEntry)
            }

            let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Time")
            let chartData = BarChartData(xVals: days, dataSet: chartDataSet)
            barChartView.data = chartData
        }
    }

This prompts an error in func setChart:

In

    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Time")

Incorrect argument in call (have yVals, expected values). But if you change yVals to values, it prompts an error in the next line:

    let chartData = BarChartData(xVals: days, dataSet: chartDataSet)

The error is: Cannot invoke initializer for type 'BarChartData' with an argument list of type '(xVals:[String]!, dataSet: BarChartDataSet)'

I took a look at ChartsDemo, but I'm not sure what I am exactly looking for (and I seem to be getting a compiling error when I try to build the demo).

Can someone help me out with this?


Solution

  • Try This

    func setChart(dataPoints: [String], values: [Double]) {
    
        barChartView.noDataText = "You need to provide data for the chart."
    
        var dataEntries: [BarChartDataEntry] = Array()
        var counter = 0.0
    
        for i in 0..<dataPoints.count {
            counter += 1.0
            let dataEntry = BarChartDataEntry(x: values[i], y: counter)
            dataEntries.append(dataEntry)
        }
    
        let chartDataSet = BarChartDataSet(values: dataEntries, label: "Time")
        let chartData = BarChartData()
        chartData.addDataSet(chartDataSet)
        barChartView.data = chartData
    
    }