Swift - 第三方图表库Charts使用详解22(饼状图2:指示折线、半饼图)
二、多义线(指示线)
默认情况下,每个扇区的文字和数值都是显示在扇区内部,如果内容一多就会显的很拥挤。我们让某些数据在饼图外边显示,并自动通过折线与对应扇区相关联。
1,基本用法
(1)标签显示在内、数值显示在外
import UIKit import Charts class ViewController: UIViewController { //饼状图 var chartView: PieChartView! override func viewDidLoad() { super.viewDidLoad() //创建饼图组件对象 chartView = PieChartView() chartView.frame = CGRect(x: 20, y: 80, width: self.view.bounds.width - 40, height: 260) self.view.addSubview(chartView) //生成5条随机数据 let dataEntries = (0..<5).map { (i) -> PieChartDataEntry in return PieChartDataEntry(value: Double(arc4random_uniform(50) + 10), label: "数据\(i)") } let chartDataSet = PieChartDataSet(values: dataEntries, label: "数据分布") //设置颜色 chartDataSet.colors = ChartColorTemplates.vordiplom() + ChartColorTemplates.joyful() + ChartColorTemplates.colorful() + ChartColorTemplates.liberty() + ChartColorTemplates.pastel() chartDataSet.xValuePosition = .insideSlice //标签显示在内 chartDataSet.yValuePosition = .outsideSlice //数值显示在外 let chartData = PieChartData(dataSet: chartDataSet) chartData.setValueTextColor(.black)//文字颜色为黑色 //设置饼状图数据 chartView.data = chartData } }
(2)标签显示在外、数值显示在内
chartDataSet.xValuePosition = .outsideSlice //标签显示在外 chartDataSet.yValuePosition = .insideSlice //数值显示在内
(3)标签、数值均显示在外面
chartDataSet.xValuePosition = .outsideSlice //标签显示在外 chartDataSet.yValuePosition = .outsideSlice //数值显示在外
2,修改折线样式
chartDataSet.valueLinePart1OffsetPercentage = 0.8 //折线中第一段起始位置相对于扇区偏移量(值越大距越远) chartDataSet.valueLinePart1Length = 0.55 //折线中第一段长度占比 chartDataSet.valueLinePart2Length = 0.2 //折线中第二段长度最大占比 chartDataSet.valueLineWidth = 1 //折线的粗细 chartDataSet.valueLineColor = UIColor.brown //折线颜色
三、扇形图
1,基本用法
import UIKit import Charts class ViewController: UIViewController { //饼状图 var chartView: PieChartView! override func viewDidLoad() { super.viewDidLoad() //创建饼图组件对象 chartView = PieChartView() chartView.frame = CGRect(x: 20, y: 80, width: self.view.bounds.width - 40, height: 260) self.view.addSubview(chartView) chartView.maxAngle = 270 //整个扇形占2/3圆 chartView.rotationAngle = 135 //旋转角度让扇面左右对称 //生成5条随机数据 let dataEntries = (0..<3).map { (i) -> PieChartDataEntry in return PieChartDataEntry(value: Double(arc4random_uniform(50) + 10), label: "数据\(i)") } let chartDataSet = PieChartDataSet(values: dataEntries, label: "数据分布") //设置颜色 chartDataSet.colors = ChartColorTemplates.colorful() let chartData = PieChartData(dataSet: chartDataSet) //设置饼状图数据 chartView.data = chartData } }
2,半饼图
chartView.maxAngle = 180 //整个扇形占1/2圆 chartView.rotationAngle = 180 //旋转角度让饼图左右对称