Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set x-axis labels with ios charts

I've recently started using the ios charts library and am having trouble finding information on how to manipulate the x-axis with the swift3 update.

What I want to do is label the x-axis with time values, e.g. 2:03:00, 2:03:01, 2:03:02, etc. In the tutorials I find online, this seems to be very easy; many of them use months of the year as the x-axis label.

However, in the swift3 update, charts now initializes values with x and y values, and I am not sure how to use labels in this version of the library. Does anyone know how to create labels in charts with swift3?

like image 717
matt Avatar asked Oct 29 '16 20:10

matt


People also ask

How do you stagger x-axis labels?

One way to solve this problem is to right-click the axis on the chart and select Format Axis from the shortcut menu. Then in the Format Axis task pane, under Labels, set the Label Position to Low. 21.

How do I add data labels to the x-axis in Excel?

From the Design tab, Data group, select Select Data. In the dialog box under Horizontal (Category) Axis Labels, click Edit. In the Axis label range enter the cell references for the x-axis or use the mouse to select the range, click OK. Click OK.


2 Answers

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
like image 184
Shrestha Ashesh Avatar answered Oct 09 '22 10:10

Shrestha Ashesh


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
like image 16
Hamed Avatar answered Oct 09 '22 11:10

Hamed