多系列柱状图,这里基本的就不说了,接着之前的文章,直接写到数据赋值的处理:
NSArray *array = @[@"17655.2", @"20939.38", @"36271.65", @"30353.48", @"26874.45", @"23715.13", @"24367.3", @"23408.85", @"24016.9", @"31424.75", @"26744.25", @"26307.8"];
NSArray *array1 = @[@"17077.85", @"18197.63", @"29818.3", @"26785.3", @"26273.75", @"22973.3", @"23457.4", @"25208.25", @"27054.9", @"32088.15", @"24960.65", @"31157.2"];
NSArray *array2= @[@"20155.2", @"19874.18", @"32059.85", @"25786.1", @"28643.8", @"26407.05", @"23894.45", @"23832.1", @"28999.18", @"35795.8", @"16169.15", @"--"];
NSMutableArray *valueArray = [NSMutableArray array];
[valueArray addObject:array];
[valueArray addObject:array1];
[valueArray addObject:array2];
double dataSetMin = 0;
double dataSetMax = 0;
float groupSpace = 0.25f;
float barSpace = 0.0f;
float barWidth = 0.25f;
NSMutableArray *dataSets = [NSMutableArray array];
for (int i = 0; i < valueArray.count; i++) {
NSMutableArray *yVals = [NSMutableArray array];
BarChartDataSet *set = nil;
NSArray *array = valueArray[i];
for (int j = 0; j < array.count; j++)
{
double val = [array[j] doubleValue];
dataSetMax = MAX(val, dataSetMax);
dataSetMin = MIN(val, dataSetMin);
[yVals addObject:[[BarChartDataEntry alloc]
initWithX:j
y:val]];
set = [[BarChartDataSet alloc] initWithValues:yVals label:[NSString stringWithFormat:@"第%d个图例",i]];
[set setColor:self.colorArray[i]];
set.valueColors = @[self.colorArray[i]];
}
[dataSets addObject:set];
}
double diff = dataSetMax - dataSetMin;
if (dataSetMax == 0 && dataSetMin == 0) {
dataSetMax = 100.0;
dataSetMin = -10.0;
} else {
dataSetMax = (dataSetMax + diff * 0.2);
dataSetMin = (dataSetMin - diff * 0.1);
}
self.barChartView.leftAxis.axisMaximum = dataSetMax;
self.barChartView.leftAxis.axisMinimum = 0;
BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
[data setValueFont:[UIFont systemFontOfSize:10.f]];
data.barWidth = barWidth;
_barChartView.xAxis.axisMinimum = -0.1;
_barChartView.xAxis.axisMaximum = 0 + [data groupWidthWithGroupSpace:groupSpace barSpace: barSpace] * 12;
[data groupBarsFromX: 0 groupSpace: groupSpace barSpace: barSpace];
_barChartView.data = nil;
_barChartView.data = data;
[self.barChartView animateWithXAxisDuration:0.25f];
效果图如下:
多系列柱状图主要的几行代码
float groupSpace = 0.25f;
float barSpace = 0.0f;
float barWidth = 0.25f;
// (barSpace + barWidth) * 系列数 + groupSpace = 1.00 -> interval per "group"
groupSpace
groupSpace -- 组的间隔
barSpace -- 每组之间柱状图的间隔
barWidth -- 每组柱状图的宽度
单系列的柱状图更简单,只需要设置barwidth就可以了 [data groupBarsFromX: 0 groupSpace: groupSpace barSpace: barSpace] 这句话可以不要,在折线和混合图表里面也有单系列的柱状图。