1
votes

I am trying to draw a piechart and want to show the labels, lets say as "Red" and "Blue".

Red has a value of 100. Blue has a value of 200.

Code is like this:

var colorEntries: [ChartDataEntry] = []
colorEntries.append(ChartDataEntry(x: 0, y: 100)) // 100 Red entires
colorEntries.append(ChartDataEntry(x: 1, y: 200)) // 200 Blue entries

// pie chart
let pieChartDataSet = PieChartDataSet(values: colorEntries.append, label: "Color Chart")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
self.pieChart.data = pieChartData

// I'm not very sure how these colors are mapped to the dataset.
let colors: [UIColor] = [UIColor(red: CGFloat(1), green: 0, blue: 0, alpha: 1),
                         UIColor(red: 0, green: 0, blue: CGFloat(1), alpha: 1)]
pieChartDataSet.colors = colors

Here is the charts framework: https://github.com/danielgindi/Charts

There are some nice tutorials on the web out there. But they are outdated. The latest release of the Charts framework introduced breaking changes (seems rather unintuitive).

Release notes: https://github.com/danielgindi/Charts/releases/tag/v3.0.0

1
Where do you want to add the Labels?Aditya Garg
Over the pie chart sections, just like the default number labels.AlvinfromDiaspar

1 Answers

3
votes

So basically you create an array of ChartDataEntry, then you loop through your list of dataPoints (An array of strings for your piechart sections) and values (Which is a corresponding array of values associated with the string of sections).

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

let pieChartDataSet = PieChartDataSet(values: dataEntries, label: nil)
let pieChartData = PieChartData(dataSet: pieChartDataSet)

self.data = pieChartData