Search code examples
iosswiftpie-chart

How to show Percentage sign in pie chart using daniel gindi/Chart library in swift(IOS Chart)


I am using the Charts framework (by Daniel gindi). It was working fine but how to show % (sign) on piechart?
I am also try use NSNumberFormatter() method for covert data value in percantage but not get % sign.
I am upload code here

    @IBOutlet var pieChart: PieChartView!
    override func viewDidLoad() {
            super.viewDidLoad()
            var data = [25.0,37.5,12.5,12.5,12.5] // pie chart data 
            var status = ["A","B","C","D","E"] // status
            setChart(status, values: data)
            self.pieChart.drawSliceTextEnabled = false

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

            pieChart.noDataText = "you need to provide data for chart"
            pieChart.noDataTextDescription = ""
            self.pieChart.descriptionText = ""

            var dataEntries: [ChartDataEntry] = []
            //pieChart.centerText = " "
            for i in 0..<dataPoints.count {

                let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
                dataEntries.append(dataEntry)

            }

            let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "")

            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

            }

            let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)

            pieChart.data = pieChartData
            pieChart.animate(yAxisDuration: 2.0, easingOption: .EaseInOutBack)
}

Output:=>

enter image description here


Solution

  • To show % sign on pieChart.

    Download Example Project

    Just use this below code.

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .PercentStyle
    formatter.maximumFractionDigits = 1
    formatter.multiplier = 1.0
    pieChartData.dataSet?.valueFormatter = formatter
    

    You will get % sign after your value display on slice.

    enter image description here

    Source https://github.com/danielgindi/Charts