iOS Question

How to add Strings on X Axis in iOS-charts?

With the new release i had some troubles to create some graphs the previous code was:

func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [BarChartDataEntry] = []

for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}

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


You can pass the values for example an array of months using the line:

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


After the new release the code to implement the same graph is:

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

var dataEntries: [BarChartDataEntry] = []

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

let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")

let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
barChartView.data = chartData

}


I was trying a few hours but i couldn't find a way to modify the X axis values, i hope someone can help me, thanks!!

Answer

I found the solution, maybe another one can solve this problem in a better way, without create a new class, well this is what I found:

First you nedd to create a new class, which will be your formatter class and add the IAxisValueFormater interface, then you use the method stringForValue to customize the new values, it takes two parameters, the first is the actual value (you can see it like the index) and second is the axis where the value is.

import UIKit
import Foundation
import Charts

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter{

var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]


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

    return months[Int(value)]
}

}

Now in your file at the begining of your setChart() function you have to create two variables one for your formatter class and one for the axis class:

let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()

Next, go ahead at the end of the for in loop and pass the index and axis to your formatter variable:

formato.stringForValue(Double(i), axis: xaxis)

After looping add the format to your axis variable:

xaxis.valueFormatter = formato

The final step is to add the new xaxisformatted to the barChartView:

barChartView.xAxis.valueFormatter = xaxis.valueFormatter

And that's all the other lines in the setChart() function just keep it where they are, I hope it can help you.

Comments