0

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

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.