Sundeep Saluja
Sundeep Saluja

Reputation: 1249

Show integer value labels in bar chart for iOS

I need to create a bar graph to display some stats data, which I am able to display using iOS charts library. Only issue I am facing is that, the value labels above the bars are printed as double, I need them as integers. I have tried searching it, but no positive results. Below is my code:

    barChartView = BarChartView()
    barChartView.frame = screen.bounds
    barChartView.delegate = self
    barChartView.backgroundColor = UIColor.clear
    barChartView.layer.opacity = 0.0
    barChartView.chartDescription?.text = ""
    self.view.addSubview(barChartView)

Any help is appreciated.

Upvotes: 3

Views: 1514

Answers (2)

Birju
Birju

Reputation: 1130

You can simply define formatter and apply that formatter to dataset like below

     NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
     pFormatter.numberStyle = NSNumberFormatterDecimalStyle;
     pFormatter.maximumFractionDigits = 100;
     pFormatter.multiplier = @1;
     BarChartDataSet *set = nil;
     set = [[BarChartDataSet alloc] initWithEntries:values label:@"Election Result"];
     [set setValueFormatter:[[ChartDefaultValueFormatter alloc]initWithFormatter:pFormatter]];

Upvotes: 0

DevB2F
DevB2F

Reputation: 5095

Make a custom formatter to change each value to Int.

class CustomIntFormatter: NSObject, IValueFormatter{
    public func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        let correctValue = Int(value)
        print("correctValue: \(correctValue)")
        return String(correctValue)
    }
}

Then set the formatter for your graph.

    let formatter: CustomIntFormatter = CustomIntFormatter()
    barChartView.data?.setValueFormatter(formatter)

Upvotes: 5

Related Questions