一个很好的图表制作第三方框架的使用:Charts
柱状图 BarChatView,创建如下图的效果
<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 />
-
初始化并进行一些配置的设置
// 柱状图
let barChartView = BarChartView().then {
$0.noDataText = "暂无统计数据" //无数据的时候显示
$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设置,x轴设置, 相应的可以设置左侧,右侧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 //左侧y轴设置,不画线
$0.leftAxis.axisMinimum = 0.0 //最小数据
$0.rightAxis.drawGridLinesEnabled = false //右侧y轴设置,不画线
$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)
-
设置图标的数据
/// 设置柱状图数据
///
/// - Parameter model: 数据
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: "发布数/月份")
chartDataSet.colors = [NavbarColor]
let chartData = BarChartData(dataSet: chartDataSet)
self.barChartView.data = chartData
self.barChartView.animate(yAxisDuration: 1.0, easingOption: .easeInBack)
}