Search code examples
iosobjective-cchartsios-charts

How to add % to Y axis values/labels in ios Charts?


I'm using IOS Charts, to plot horizontal bar chart, with 2 y-values.I have a requirement of adding '%' symbol to both y-values showing beside the bars, and even on Y-Axis(RightAxis) How to do that ? Here is my graph image[Horizontal Bar chart that I drew][1]And I'm drawing this plot using objective-C but using Swift framework. Here is the link for the charts I'm using https://github.com/danielgindi/Charts

I added this bottom lines to my code as advised by creativ

NSNumberFormatter *formater = [[NSNumberFormatter alloc] init];
formater.numberStyle = NSNumberFormatterPercentStyle;

_graphContainerView.rightAxis.valueFormatter = formater;

But the problem is I'm getting values beside each bar as decimal points as shown in below Image but I want them also in percentage values here is my code

-(void)setDataForXAxis:(NSMutableArray*)xVals benchMarkValues:(NSMutableArray*)benchMarkVals percentageValues:(NSMutableArray*)percentVals This image is after adding the below code{

NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
NSMutableArray *yVals2 = [[NSMutableArray alloc] init];

for (int i = 0; i < xVals.count; i++)
{
    NSNumber *val = [benchMarkVals objectAtIndex:i];
    [yVals1 addObject:[[BarChartDataEntry alloc] initWithValue:val.doubleValue/100 xIndex:i]];

    val = [percentVals objectAtIndex:i];
    [yVals2 addObject:[[BarChartDataEntry alloc] initWithValue:val.doubleValue/100 xIndex:i]];
}

BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithYVals:yVals1 label:@"Sectoral \nBreakdown(Benchmark)"];
[set1 setColor:[UIColor colorWithRed:236/255.f green:205/255.f blue:118/255.f  alpha:1.f]];
BarChartDataSet *set2 = [[BarChartDataSet alloc] initWithYVals:yVals2 label:@"Sectoral \nBreakdown(%)"];
[set2 setColor:[UIColor colorWithRed:31/255.f green:125/255.f blue:184/255.f alpha:1.f]];
set2.barSpace = set1.barSpace = 0;

NSMutableArray *dataSets = [[NSMutableArray alloc] init];
[dataSets addObject:set1];
[dataSets addObject:set2];

BarChartData *data = [[BarChartData alloc] initWithXVals:xVals dataSets:dataSets];
data.groupSpace = 1.1;
[data setValueFont:[UIFont fontWithName:kUTLightFontName size:6.f]];
_graphContainerView.data = data;

}


Solution

  • You can change the valueFormatter of the y-Axis to include the % symbol. E.g. set the valueFormatter to a custom NSNumberFormatter and set the numberStyle to NSNumberFormatterPercentStyle.

    Note that you might have to change your values to a value between 0-1 instead of 0-100. I can't test it right now, but I think you could also set the multiplier of the valueFormatter to 1 and it should work with values between 0-100.

    In order to change the formatter for the individual bars, you need to change the valueFormatter of the DataSet.