swiftpie-chartios-charts

Swift PieChartView - Values are not shown with percentage % sign


I'm using PieChartView from DGCharts library to draw a simple pie chart. The values i show are correct but i would like to add the percentage sign (%) to each.

I tried the following code and as you can see in the NumberFormatter i specified to show the percentage sign, but it doesn't appear, i instead only get the numerical values.

// 1. Set ChartDataEntry
  var dataEntries: [ChartDataEntry] = []
     for i in 0..<dataPoints.count {
        let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i], data: dataPoints[i] as AnyObject)
            dataEntries.append(dataEntry)
     }


// 2. Set ChartDataSet
let pieChartDataSet = PieChartDataSet(entries: dataEntries, label: "")
    pieChartDataSet.colors = [.orange, .veryLightPinkFour]
    pieChartDataSet.selectionShift = 0
        
// 3. Set ChartData
let pieChartData = PieChartData(dataSet: pieChartDataSet)

let format = NumberFormatter()
    format.numberStyle = .percent
    format.maximumFractionDigits = 0
    format.multiplier = 1.0
    format.percentSymbol = "%"
    format.zeroSymbol = ""

let formatter = DefaultValueFormatter(formatter: format)
    pieChartData.setValueFormatter(formatter)
     pieChartData.dataSet?.valueFormatter = formatter
        
// 4. Assign it to the chart's data
 pieChartView.data = pieChartData

Solution

  • You must assign valueFormatter after pieChartView.data = pieChartData to make it works. Maybe there is a bug here, it also happened on their demo.

    pieChartView.data = pieChartData
    
    pieChartData.setValueFormatter(DefaultValueFormatter(formatter: format))
    
    //Or
    //pieChartData.dataSet?.valueFormatter = DefaultValueFormatter(formatter: pFormatter)