Home > Software design >  How to set specific color to each slice of Pie Chart?
How to set specific color to each slice of Pie Chart?

Time:09-21

I am using Charts library in my project to show Pie chart. For now it shows random color for every slices, but i want to set specific color for every slice, how can i do that? Here is my code so far:

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<values.count {
        let dataEntry1 = PieChartDataEntry(value: values[i])
        dataEntries.append(dataEntry1)
    }

    let pieChartDataSet = PieChartDataSet(entries: dataEntries, label: "Units Sold")
    let pieChartData = PieChartData(dataSet: pieChartDataSet)
    pieChartData.setValueTextColor(NSUIColor.clear)
    pieChartView.data = pieChartData

    var colors: [UIColor] = []

    for _ in 0..<dataPoints.count {
        
        let red = Double(arc4random_uniform(256))
        let green = Double(arc4random_uniform(256))
        let blue = Double(arc4random_uniform(256))

        let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
        colors.append(color)
    }

    pieChartDataSet.colors = colors

    pieChartView.transparentCircleColor = UIColor.clear
    
}

CodePudding user response:

You have a random color for your slices because you set a random color below for each dataPoint

for _ in 0..<dataPoints.count {
    
    let red = Double(arc4random_uniform(256))
    let green = Double(arc4random_uniform(256))
    let blue = Double(arc4random_uniform(256))

    let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
    colors.append(color)
}

If you need a specific color, then you need to set a specific color to the colors respective to each dataPoint. For an example if you have five data points, you need to have a colors array like below, so every time the slice for first dataPoint would be red, slice for second dataPoint is orange etc.

let colors: [UIColor] = [.red, .orange, .blue, .gray, .purple]
pieChartDataSet.colors = colors

enter image description here

  • Related