一個很好的圖表制作第三方框架的使用:Charts
柱狀圖 BarChatView,創(chuàng)建如下圖的效果
<img src="http://upload-images.jianshu.io/upload_images/970635-e98717b6401022cf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "300" height = "200" alt="柱狀圖" align=center />
-
初始化并進行一些配置的設(shè)置
// 柱狀圖
let barChartView = BarChartView().then {
$0.noDataText = "暫無統(tǒng)計數(shù)據(jù)" //無數(shù)據(jù)的時候顯示
$0.chartDescription?.enabled = false //是否顯示描述
$0.pinchZoomEnabled = true
$0.drawBarShadowEnabled = true
$0.drawGridBackgroundEnabled = true
let xAxisFormatter = NumberFormatter()
xAxisFormatter.minimumFractionDigits = 0
xAxisFormatter.maximumFractionDigits = 1
xAxisFormatter.negativePrefix = "月"
xAxisFormatter.positiveSuffix = "月"
//chart設(shè)置,x軸設(shè)置, 相應(yīng)的可以設(shè)置左側(cè)玉转,右側(cè)y軸
let xAxis = $0.xAxis
xAxis.labelPosition = .bottom //x軸的位置
xAxis.labelFont = .systemFont(ofSize: 10)
xAxis.drawGridLinesEnabled = false
xAxis.granularity = 1.0
// xAxis.labelCount = 12
xAxis.valueFormatter = DefaultAxisValueFormatter(formatter: xAxisFormatter)
$0.leftAxis.drawGridLinesEnabled = false //左側(cè)y軸設(shè)置,不畫線
$0.leftAxis.axisMinimum = 0.0 //最小數(shù)據(jù)
$0.rightAxis.drawGridLinesEnabled = false //右側(cè)y軸設(shè)置喻圃,不畫線
$0.rightAxis.axisMinimum = 0.0
//下方的說明
$0.legend.enabled = true
let legend = $0.legend
legend.horizontalAlignment = .left
legend.verticalAlignment = .bottom
legend.orientation = .horizontal
legend.drawInside = false
legend.form = .square
legend.formSize = 9.0
legend.font = .systemFont(ofSize: 10)
legend.xEntrySpace = 4.0
}
-
添加到視圖中
self.contentView.addSubview(self.barChartView)
self.barChartView.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.width.height.equalTo(screeW-20)
$0.top.equalTo(self.segcontrol.snp.bottom).offset(10)
}
self.setBarChartViewData(withModel: model)
-
設(shè)置圖標的數(shù)據(jù)
/// 設(shè)置柱狀圖數(shù)據(jù)
///
/// - Parameter model: 數(shù)據(jù)
func setBarChartViewData(withModel model: ChartModels) {
let charArray = model.chatDatas
var dataEntris = [BarChartDataEntry]()
for chart in charArray {
let dataEntry = BarChartDataEntry(x: Double(chart.month), y: Double(chart.count))
dataEntris.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntris, label: "發(fā)布數(shù)/月份")
chartDataSet.colors = [NavbarColor]
let chartData = BarChartData(dataSet: chartDataSet)
self.barChartView.data = chartData
self.barChartView.animate(yAxisDuration: 1.0, easingOption: .easeInBack)
}