Swift iOS Charts - Hide certain Bar Chart value labels

Viewed 1117

I am using the 'Charts' framework for my iOS app using swift and I am using the Bar Chart on one of my VCs but it looks quite messy at the moment because it displays the value labels for every value, even if it's 0. I was wondering if it's possible to only show the labels if the value is above 0? I have been looking at other questions but I can't seem to find an answer for this. I know I can hide all of the labels using chartData.setDrawValues(false) however, I still want to display the values when they are above 0.

enter image description here

This is my current code to format the chart -

    barChart.highlightPerTapEnabled = false
    barChart.highlightPerDragEnabled = false
    barChart.leftAxis.drawAxisLineEnabled = true
    barChart.leftAxis.drawGridLinesEnabled = false
    barChart.xAxis.labelPosition = .bottom
    barChart.xAxis.centerAxisLabelsEnabled = true
    barChart.xAxis.axisMinimum = 0
    barChart.xAxis.axisMaximum = 7
    barChart.xAxis.drawAxisLineEnabled = true
    barChart.xAxis.drawGridLinesEnabled = true
    barChart.rightAxis.enabled = false
    barChart.leftAxis.axisMinimum = 0

I thought about doing something like this -

 for value in chartDataSet.entries {
    if value.y == 0 {
      chartDataSet.drawValuesEnabled = false
    }
    else {
      chartDataSet.drawValuesEnabled = true
    }
 }

but of course this doesn't work as it sets the boolean for the whole set.

Any help would be much appreciated! Thanks

1 Answers

You just need to provide your custom IValueFormatter to BarChartData as below,

public class XValueFormatter: NSObject, IValueFormatter {

    public func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        return value <= 0.0 ? "" : String(describing: value)
    }
}

let chartData = BarChartData(dataSet: yourSet)
chartData.setValueFormatter(XValueFormatter())

Note: String(describing: value) is just to provide a workable example. You can apply proper number formatter to convert Double into String.

Related