Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different colors for bars in BarChart depend on value

How can I change the color of a single bar, dependent on its value, in a bar chart? For example: I have five different values (= five different bars) in my bar chart. All bars that have a value less than 30 should be red, all bars between 30 and 70 orange, and all bars above 70 should be green.

like image 331
OSX55 Avatar asked Nov 05 '16 10:11

OSX55


People also ask

How do I change the color of my bar chart based on value?

Select the bar chart or column chart, then click Kutools > Charts > Color Chart by Value. Then in the popped-out dialog, set the value range and the relative color as you need.

How do I make each bar in a bar chart different colors?

In a chart, click to select the data series for which you want to change the colors. On the Format tab, in the Current Selection group, click Format Selection. tab, expand Fill, and then do one of the following: To vary the colors of data markers in a single-series chart, select the Vary colors by point check box.

Should a bar graph have different colors?

In a bar graph, make your largest quantity the brightest color with each subsequent category being less and less saturated. Choices like these can really draw attention to where you want it to be. Stick to a few colors and use contrast to highlight important information. Don't use more than six colors together, though.

Which parameter is used to give the Colour in a bar chart?

col: This parameter is used to give colors to the bars in the graph.


1 Answers

In ios-charts, the colors of the bars are set in an array. If your dataset is called barChartDataset, for example, you would set the colors like this

barChartDataset.colors = [UIColor.red,UIColor.orange,UIColor.green,UIColor.black,UIColor.blue]

The bars will have these colors in this order and will repeat. So if you have 10 bars, you would have 2 red bars etc.

In your case, you just have to write a function to return the right color value, and attach it to the array. Reference the code below.

func setColor(value: Double) -> UIColor{

    if(value < 30){
        return UIColor.red
    }
    else if(value <= 70 && value >= 30){
        return UIColor.orange
    }
    else if(value > 70){
        return UIColor.green
    }

    else { //In case anything goes wrong
    return UIColor.black
    }
}

And then wherever you are setting the chart use

 barChartDataset.colors = [setColor(barOneValue),setColor(barTwoValue),setColor(barThreeValue),setColor(barFourValue),setColor(barFiveValue)]

Hope this helps!

like image 142
Aditya Garg Avatar answered Oct 15 '22 20:10

Aditya Garg