Different colors for bars in BarChart depend on value

眉间皱痕 提交于 2019-12-05 05:41:34

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!

Their API also comes with some predefined color templates you can use to set different colors for the data set. They include:

  • ChartColorTemplates.liberty()
  • ChartColorTemplates.joyful()
  • ChartColorTemplates.pastel()
  • ChartColorTemplates.colorful()
  • ChartColorTemplates.vordiplom()

You can use them this way :

chartDataSet.colors = ChartColorTemplates.colorful()

Reference : https://www.appcoda.com/ios-charts-api-tutorial/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!