1

I'm trying to create a line chart that has data from the last year. I want to make the labels on the xAxis of the chart represent the months from the last year, which seems to be done easily enough in this tutorial: https://www.codebeaulieu.com/96/How-to-create-a-Combined-Bar-and-Line-chart-using-ios-charts. However, this line of code from the tutorial:

let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)

where "months" represents an array of strings, is not available after the chart's update to Swift 2.3. The only constructors available for LineChartData are these two:

LineChartData(dataSets: <[IChartDataSet]?>)
LineChartData(dataSet: IChartDataSet?)

so it appears that the option for changing the xVals has disappeared after the update. Was this option moved somewhere else? Or has it been completely removed from iOS Charts?

tdon
  • 1,421
  • 15
  • 24
  • 1
    You can find the solution in below link [link](http://stackoverflow.com/questions/39049188/how-to-add-strings-on-x-axis-in-ios-charts) – Lun Sep 24 '16 at 10:17

1 Answers1

3

After giving up for a while, I finally found the solution. You have to make an IAxisValueFormatter and implement the stringForValue function. For example, I wanted to format my graph to display the last 12 months based on the current month. Here is my value formatter:

import UIKit
import Charts

class MonthNumberFormatter: NSObject, IAxisValueFormatter {

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

    convenience init(startMonthIndex: Int){
        self.init()
        self.startMonthIndex = startMonthIndex
    }

    private func getMonth(index: Int) -> Int{
        return (index % months.count)
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String{
        let monthIndex:Int = self.getMonth(index: Int(value) + self.startMonthIndex)
        let month = months[monthIndex]
        return month
    }
}

Then in your chart class --> to get the current month:

func getCurrentMonth()->Int? {
    let todayDate = Date()
    let myCalendar = NSCalendar(calendarIdentifier: .gregorian)
    let myComponents = myCalendar?.components(.month, from: todayDate)
    let month = myComponents?.month
    return month
}

Now set the values on the graph

let xAxis = self.chartView.xAxis
let currentMonth = getCurrentMonth()
xAxis.valueFormatter = MonthNumberFormatter(startMonthIndex: currentMonth!)
tdon
  • 1,421
  • 15
  • 24