Search code examples
iosswiftbar-chartios-charts

iOS Charts, Horizontal bars not accurate


I'm trying to get a horizontal bar chart, with real-time data changes. I got this problem though.

enter image description here

as you can see all the bars are inaccurate except for the longest one.

Following, my code.

class HorizontalBarChartViewController: UIViewController {

var values: [Double] = [0.0, 0.0, 0.0, 0.0, 0.0]
var moods = ["Annoiato", "Ansioso", "Stanco", "Triste", "Altro"]

@IBOutlet weak var chart: HorizontalBarChartView!

func updateCharts() {
    var chartDataEntry = [BarChartDataEntry]()

    for i in 0..<values.count {
        let value = BarChartDataEntry(x: Double(i), y: values[i])
        chartDataEntry.append(value)
    }

    let chartDataSet = BarChartDataSet(values: chartDataEntry, label: "Sigarette fumate")
    chartDataSet.drawValuesEnabled = false
    chartDataSet.colors = [NSUIColor.green]

    let chartMain = BarChartData()
    chartMain.barWidth = 0.1

    chartMain.addDataSet(chartDataSet)
    chart.animate(yAxisDuration: 0.5)
    chart.data = chartMain
}

func configureCharts() {
    chart.xAxis.valueFormatter = IndexAxisValueFormatter(values: moods)
    chart.xAxis.granularity = 1.0
    chart.xAxis.labelPosition = .bottom
    chart.xAxis.drawGridLinesEnabled = false

    chart.leftAxis.enabled = false
    chart.rightAxis.granularity = 1.0
    chart.rightAxis.axisMinimum = 0.0


    guard let description = chart.chartDescription else {return}
    description.text = ""
}

}

for increasing the values, I've got 5 of these functions, each for every values:

    @IBAction func *nameValue*Button(_ sender: UIButton) {
    values[*index*]+=1
    updateCharts()
    configureCharts()
}

how can I match the bars with the correct grid line of the right y axis?


Solution

  • Here is the solution. Please check:

    func configureCharts() {
        chart.xAxis.valueFormatter = IndexAxisValueFormatter(values: moods)
        chart.xAxis.granularity = 1.0
        chart.xAxis.labelPosition = .bottom
        chart.xAxis.drawGridLinesEnabled = false
    
        chart.rightAxis.granularity = 1.0
        chart.rightAxis.axisMinimum = 0.0
        chart.leftAxis.axisMinimum = 0.0    //here's the missing line
    
        guard let description = chart.chartDescription else {return}
        description.text = ""
    }