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

时间:2017-03-01 05:22:46

标签: ios charts ios-charts

我正在尝试画一个饼图并想要显示标签,让我们说" Red"和"蓝"。

红色的值为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

1 个答案:

答案 0 :(得分:2)

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

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