Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize datapoint labels in iOS Charts?

I'm trying to make my datapoint labels in a linechart display a custom string instead of their actual number (using the iOS Charts/ Charts library). I want to know if there is something like IAxisFormatter which I used to format my x and y axis labels.

I was wondering if anyone knows how exactly to do that in Swift? I can't seem to find any examples online. Thanks!

like image 966
holycamolie Avatar asked Apr 05 '17 19:04

holycamolie


1 Answers

You have to append IValueFormatter protocol to your ViewController and implement stringForValue(_:entry:dataSetIndex:viewPortHandler:) method (1).

Then set ViewController as valueFormatter delegate for charts data set (2).

import UIKit
import Charts

class ViewController: UIViewController, IValueFormatter {

    @IBOutlet weak var lineChartView: LineChartView!

    // Some data
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let unitsSold = [20.0, 4.0, 3.0, 6.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]

    // (1) Implementation the delegate method for changing data point labels. 
    func stringForValue(_ value: Double,
                        entry: ChartDataEntry,
                        dataSetIndex: Int,
                        implement delegate methodviewPortHandler: ViewPortHandler?) -> String{

        return "My cool label " + String(value)
    }

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

        // Prepare data for chart
        for i in 0..<dataPoints.count {
            let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
            dataEntries.append(dataEntry)
        }

        let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
        let lineChartData = LineChartData(dataSets: [lineChartDataSet])

        // (2) Set delegate for formatting datapoint labels
        lineChartData.dataSets[0].valueFormatter = self

        lineChartView.data = lineChartData
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setChart(dataPoints: months, values: unitsSold)
    }
}
like image 63
AlexSmet Avatar answered Sep 30 '22 20:09

AlexSmet