X Axis values being repeated rather than replaced iOS Charts

1.4k Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

I fixed the issue myself by adding

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