简体   繁体   中英

iOS-charts stacked bar chart with multiple colors

I am trying to create a stacked bar chart with different colors for each bar. It works fine if I provide only two colors in the BarChartDataSet , or if I have a normal bar chart with a color for every bar. However I wonder how I can provide two colors for each BarChartDataEntry in the data set?

take a look at ChartsDemo's stacked bar chart view controller: Just feed the colors to BarChartDataSet.colors

for (int i = 0; i < count; i++)
{
    double mult = (range + 1);
    double val1 = (double) (arc4random_uniform(mult) + mult / 3);
    double val2 = (double) (arc4random_uniform(mult) + mult / 3);
    double val3 = (double) (arc4random_uniform(mult) + mult / 3);

    [yVals addObject:[[BarChartDataEntry alloc] initWithValues:@[@(val1), @(val2), @(val3)] xIndex:i]];
}

BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithYVals:yVals label:@"Statistics Vienna 2014"];
set1.colors = @[ChartColorTemplates.vordiplom[0], ChartColorTemplates.vordiplom[1], ChartColorTemplates.vordiplom[2]];
set1.stackLabels = @[@"Births", @"Divorces", @"Marriages"];

In bar chart renderer it is using this colors array to fill each segment,

// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)

If you want each bar has different color, then you have to use multiple data sets and perhaps adjust barSpace and groupSpace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM