How to set x-axis labels with ios charts
Proper Solution for X-Axis String labels in Swift 3+
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:months) barChartView.xAxis.granularity = 1
Create a class like this:
import Foundation import Charts @objc(BarChartFormatter) class ChartFormatter:NSObject,IAxisValueFormatter{ var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] func stringForValue(_ value: Double, axis: AxisBase?) -> String { return months[Int(value)] }}
Set the x-Axis like this:
let xAxis=XAxis() let chartFormmater=ChartFormatter() for i in index{ chartFormmater.stringForValue(Double(i), axis: xAxis) } xAxis.valueFormatter=chartFormmater chartView.xAxis.valueFormatter=xAxis.valueFormatter
I propose to use more flexible and pretty solution. You should have a formatter class like this:
final class MonthNameFormater: NSObject, IAxisValueFormatter { func stringForValue( _ value: Double, axis _: AxisBase?) -> String { return Calendar.current.shortMonthSymbols[Int(value)] }}
Set up this type to your barChartView
:
barChartView.xAxis.valueFormatter = MonthNameFormater()barChartView.xAxis.granularity = 1.0
As a result you will have: Jan, Feb, ..., Dec
In addition if you want to change presentation kind you should change shortMonthSymbols with some other: monthSymbols, veryShortMonthSymbols, standaloneMonthSymbols