如何使用 iOS 的图表库在饼图中显示字符串标签?

How to show string labels in a PieChart using the Charts library for iOS?

我正在尝试绘制饼图并希望显示标签,假设为 "Red" 和 "Blue"。

红色的值为 100。 蓝色的值为 200。

代码是这样的:

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

这是图表框架:https://github.com/danielgindi/Charts

网上有一些不错的教程。但是它们已经过时了。最新版本的 Charts 框架引入了重大变化(似乎相当不直观)。

发行说明:https://github.com/danielgindi/Charts/releases/tag/v3.0.0

所以基本上您创建了一个 ChartDataEntry 数组,然后循环遍历您的数据点列表(饼图部分的字符串数组)和值(这是与部分字符串关联的相应值数组)。

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