Search code examples
iosswiftchartsios-charts

How to set correct labels is iOS Charts bar chart and colour columns to suit?


I have an iOS Chart, as per the image below, and the labels are showing incorrectly (or not what I want).

enter image description here

As you can see they both say 'Games Played' and are the same colour, as is each bar in my graph.

How can I change the colour of each bar and show the correct respective labels, 'Won', 'Drawn', 'Lost'?

This is my code:

override func viewDidLoad() {
   super.viewDidLoad()

   let results =  ["Won", "Drawn", "Lost"]
   let games = [totalWins, totalDraws, totalLosses]
   setChart(dataPoints: results, values: games)
}

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

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

    barChartView.noDataText = "you need to provide some data for the chart."

    var dataEntries: [BarChartDataEntry] = Array()

    for i in 0..<dataPoints.count {
        let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
        dataEntries.append(dataEntry)
        formato.stringForValue (Double(i), axis: xaxis)
    }

    xaxis.valueFormatter = formato
    barChartView.xAxis.valueFormatter = xaxis.valueFormatter

    let chartDataSet = BarChartDataSet(values: dataEntries, label: "Games Played")
    let chartData = BarChartData(dataSets: [chartDataSet])

    chartData.addDataSet(chartDataSet)
    barChartView.data = chartData
    barChartView.leftAxis.forceLabelsEnabled = true
    barChartView.rightAxis.forceLabelsEnabled = true

    barChartView.xAxis.granularityEnabled = true
    barChartView.xAxis.granularity = 1.0

    barChartView.leftAxis.drawGridLinesEnabled = false
    barChartView.rightAxis.drawGridLinesEnabled = false
    barChartView.xAxis.drawGridLinesEnabled = false

    barChartView.rightAxis.enabled = false
    barChartView.drawGridBackgroundEnabled = false
    self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom

}

Solution

  • Simply add chartDataSet.colors = ChartColorTemplates.material() or you can add your array of UIColor in order to customise according to your need.