pkc
pkc

Reputation: 8516

How to set x-axis on bar chart data - ios-charts?

Previously we can set the x-Axis of bar chart data as below:-

BarChartData *data = [[BarChartData alloc] initWithXVals:xvals dataSets:dataSets];

In latest updated of ios-charts library, the syntax changed to below:- BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];

How to set the x axis on BarChartData?

Upvotes: 3

Views: 1885

Answers (2)

pkc
pkc

Reputation: 8516

With the help of this Answer (swift version), I am able to show xAxis string values on bar chart in Objective-C.

NSMutableArray *xValsDietArray;

Set up your chart data. Basic example is as follows:-

for (int i=0; i<dietArray.count; i++) {
    DietInput *obj = [dietArray objectAtIndex:i];
    NSString *dateStr = @"Jan";
    [xValsDietArray addObject:dateStr];//Maintain this xValsDietArray. It will be used later on while setting x values. This contains array of x-axis values
    [yvals addObject:[[BarChartDataEntry alloc]initWithX:[[xValsDietArray objectAtIndex:i] doubleValue] y:obj.calorieInput.doubleValue data:xValsDietArray] ];
}

BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithValues:yvals label:@"Water Consumed"];
NSMutableArray *dataSets = [[NSMutableArray alloc] init];
[dataSets addObject:set1];
BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
cell.chartView.data=data;
cell.chartView.xAxis.valueFormatter = self;// Set the delegate to self. THIS IS THE MAIN ADDITION IN NEW CHART LIBRARY

Implement the stringForValue delegate method as follows:-

- (NSString * _Nonnull)stringForValue:(double)value axis:(ChartAxisBase * _Nullable)axis
{
    NSString *xAxisStringValue = @"";
    int myInt = (int)value;

    if(xValsDietArray.count > myInt)
        xAxisStringValue = [xValsDietArray objectAtIndex:myInt];

    return xAxisStringValue;
}

Upvotes: 3

CodeChanger
CodeChanger

Reputation: 8351

You can use below same method of IAxisValueFormatter with value as index and fetch data from xArray and show your custom X values in it.

#pragma mark - IAxisValueFormatter

- (NSString *)stringForValue:(double)value
                        axis:(ChartAxisBase *)axis
{
    NSString *xValue = [xArray objectAtIndex:value];
    return xValue;
}

You can use this as delegate methods of IAxisValueFormatter.

Hope this will helps you to set xAxis in your chart.

Upvotes: 1

Related Questions