Reputation: 170
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.
Upvotes: 10
Views: 8709
Reputation: 326
In danielgindi charts the bar chart, bar color can be changed from "ChartColorTemplate.swift" file in the following code -
@objc open class func material () -> [NSUIColor]
{
return [
NSUIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0),
NSUIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0),
NSUIColor(red: 231/255.0, green: 76/255.0, blue: 60/255.0, alpha: 1.0),
NSUIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0)
]
}
Upvotes: -1
Reputation: 858
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!
Upvotes: 22
Reputation: 2419
Their API also comes with some predefined color templates you can use to set different colors for the data set. They include:
You can use them this way :
chartDataSet.colors = ChartColorTemplates.colorful()
Reference : https://www.appcoda.com/ios-charts-api-tutorial/
Upvotes: 1