4
votes

The values on the the axis seem to be repeated rather than being replaced as you can see in the screenshot below it should be plotting the "Jan", "Feb", "Mar", "Apr", "May", "Jun" rather than the result in the simulator.

enter image description here

Here is the code

class ViewController: UIViewController {

    @IBOutlet weak var chartContainer: LineChartView!
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 3.0]


    override func viewDidLoad() {
        super.viewDidLoad()


        setChart(dataPoints: months, values: unitsSold)



    }

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

        // Set up x axis
        let xaxis = XAxis()
        let chartFormatter = ChartFormatter(myArr: months)

        // Array for entries
        var dataEntries: [ChartDataEntry] = []

        // Add new data entries
        for i in 0..<dataPoints.count {

            let dataEntry = ChartDataEntry(x: Double(i) , y: values[i], data: "a" as AnyObject? )

            dataEntries.append(dataEntry)
            chartFormatter.stringForValue(Double(i), axis: xaxis)
        }

        xaxis.valueFormatter = chartFormatter
        chartContainer.xAxis.valueFormatter = xaxis.valueFormatter

        // Configure the dataset
        let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
        let lineChartData = LineChartData(dataSet: lineChartDataSet)




        chartContainer.data = lineChartData



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

@objc(ChartFormatter)
class ChartFormatter: NSObject, IAxisValueFormatter {

    private var myArr: [String]!

    init(myArr: [String]) {


        self.myArr = myArr
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {

        return myArr[Int(value)]
    }
}
1
A bit of a guess on my part because I am not familiar with ChartFormatter but it 'feels like' a rounding error. Can you use the debugger to verify that stringForValue() indeed gets values 0, 1, 2, etc in sequence which are then associated to the appropriate value in myArr[] ?Yohst
@Yohst without manipulating the xaxis values are decimal pointsTunds

1 Answers

6
votes

I fixed the issue myself by adding

   chartContainer.xAxis.granularityEnabled = true
   chartContainer.xAxis.granularity = 1.0