iOS Charts庫的簡單使用 - BarChartView
iOS Charts庫的簡單使用 - PieChartView
iOS Charts庫的簡單使用 - LineChartView
iOS Charts庫的簡單使用 - CombinedChartView
Charts 庫各類之間屬性基本互通,可相互參考,更多屬性參看 iOS Charts庫的簡單使用 - BarChartView
更多使用方法及屬性參考 MPAndroidChart
文檔:MPAndroidChart Documentation
最后附上 demo,demo有個(gè)別錯(cuò)誤未修改,請(qǐng)甄別。
BarChartView
的部分屬性及簡單使用
開局一張簡單的柱狀圖
let barChartView = BarChartView(frame: CGRect(x: 0, y: 500, width: UIScreen.main.bounds.width, height: 200))
view.addSubview(barChartView)
var entries = [BarChartDataEntry]()
for i in 0...10 {
let entry = BarChartDataEntry(x: Double(i), y: Double(arc4random_uniform(50)))
entries.append(entry)
}
let set = BarChartDataSet(entries: entries, label: "圖例")
let data = BarChartData(dataSet: set)
barChartView.data = data
HorizontalBarChartView
BarChartView
屬性
//柱狀條后面畫一個(gè)灰色區(qū)域,表示最大值。默認(rèn) false
barChartView.drawBarShadowEnabled = true
//顯示頂部文字。默認(rèn) true
barChartView.drawValueAboveBarEnabled = false
//在圓柱左右兩端各增加一半的條寬。默認(rèn) false
barChartView.fitBars = true
// x、y軸動(dòng)畫
barChartView.animate(xAxisDuration: 1)
barChartView.animate(yAxisDuration: 1)
//barChartView.animate(xAxisDuration: 1, yAxisDuration: 1)
//空表時(shí)顯示的文字
barChartView.noDataText = "暫無數(shù)據(jù)"
//空表時(shí)顯示的文字大小
barChartView.noDataFont = .systemFont(ofSize: 20)
//空表時(shí)顯示的文字顏色
barChartView.noDataTextColor = .orange
//空表時(shí)顯示的文字位置
barChartView.noDataTextAlignment = .center
//平移拖動(dòng)。默認(rèn) true
barChartView.dragEnabled = true
//x軸滑動(dòng)(包括放大后)。默認(rèn)true
//barChartView.dragXEnabled = true
//y軸滑動(dòng)(包括放大后)。默認(rèn)true
//barChartView.dragYEnabled = true
//x軸縮放 默認(rèn)true
barChartView.scaleXEnabled = true
//y軸縮放 默認(rèn)true
barChartView.scaleYEnabled = true
//觸控放大
barChartView.pinchZoomEnabled = false
//雙擊放大圖表。默認(rèn)true
barChartView.doubleTapToZoomEnabled = true
//拖動(dòng)后圖表是否繼續(xù)滾動(dòng)。默認(rèn)true
barChartView.dragDecelerationEnabled = true
//減速摩擦系數(shù),間隔0-1,如果將其設(shè)置為0,它將立即停止,1是無效值,并將自動(dòng)轉(zhuǎn)換為0.9999。默認(rèn)0.9
barChartView.dragDecelerationFrictionCoef = 0.9
//當(dāng)圖表完全縮小的時(shí)候,每一次拖動(dòng)都會(huì)高亮顯示在圖標(biāo)視圖上。默認(rèn)true
barChartView.highlightPerDragEnabled = true
//設(shè)置最大高亮距離(dp)。在圖表中的點(diǎn)擊位置距離條目的距離超過此距離不會(huì)觸發(fā)高亮顯示。默認(rèn)500
barChartView.maxHighlightDistance = 500
//設(shè)置為false后,禁止點(diǎn)擊手勢(shì)高亮顯示值,值仍然可以通過拖動(dòng)或編程方式突出顯示。默認(rèn)true
barChartView.highlightPerTapEnabled = true
//y軸自動(dòng)縮放
barChartView.autoScaleMinMaxEnabled = false
//是否繪制網(wǎng)格背景。默認(rèn)false
barChartView.drawGridBackgroundEnabled = true
//網(wǎng)格背景顏色
barChartView.gridBackgroundColor = .purple
//是否繪制圖表邊框,繪制后就不需要繪制x軸和y軸的軸線了。默認(rèn)false
barChartView.drawBordersEnabled = true
//圖表邊框顏色。默認(rèn)black
barChartView.borderColor = .red
//圖表邊框?qū)挾取DJ(rèn)1.0
barChartView.borderLineWidth = 3
//默認(rèn)NO
barChartView.clipValuesToContentEnabled = false
//false時(shí),則柱狀圖(x軸線)下方不裁剪突出的顯示(圖表放大后可看出效果)。默認(rèn)true
barChartView.clipDataToContentEnabled = true
//圖表周圍的最小偏移量,值越大圖表越小。
barChartView.minOffset = 50
//圖表偏移量(上)。
barChartView.extraTopOffset = 50
//圖表偏移量(下)。
barChartView.extraBottomOffset = 50
//圖表偏移量(左)。
barChartView.extraLeftOffset = 50
//圖表偏移量(右)。
barChartView.extraRightOffset = 50
//barChartView.setExtraOffsets(left: 0, top: 0, right: 0, bottom: 0)
//默認(rèn)YES
barChartView.drawMarkers = true
let markerView = MarkerView()
markerView.chartView = barChartView;
barChartView.marker = markerView;
//自定義的maskView
let maskView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
maskView.backgroundColor = .red
markerView.addSubview(maskView)
let chartDescription = Description()
chartDescription.position = CGPoint(x: 220, y: 120)
chartDescription.text = "圖表描述文字"
chartDescription.textAlign = .right
chartDescription.font = .systemFont(ofSize: 30)
chartDescription.textColor = .red
barChartView.chartDescription = chartDescription
//是否有圖例。默認(rèn)true
barChartView.legend.enabled = true
barChartView.legend.formSize = 20
barChartView.legend.font = .systemFont(ofSize: 30)
barChartView.legend.textColor = .red
barChartView.legend.horizontalAlignment = .right
barChartView.legend.orientation = .vertical
//換行
barChartView.legend.wordWrapEnabled = true
//比例
barChartView.legend.maxSizePercent = 0.95
//僅適用于堆疊式(stacked),當(dāng)為true時(shí),點(diǎn)擊圓柱時(shí)即使只選中了一個(gè)堆棧條目,也會(huì)高亮整條圓柱。默認(rèn)false
barChartView.highlightFullBarEnabled = false
//繪制值的最大項(xiàng)數(shù),大于此值的條目號(hào)將導(dǎo)致value-label消失。默認(rèn)100
barChartView.maxVisibleCount = 100
//刷新圖表
barChartView.notifyDataSetChanged()
barChartView.data?.notifyDataChanged()
xAxis
x軸
let xAxis = barChartView.xAxis
//是否顯示x軸。默認(rèn)true
xAxis.enabled = true
//默認(rèn)5.0
xAxis.xOffset = 5.0
//偏移量。改變值時(shí)文字位置不變,圖表整體上移或下移距離的大小。默認(rèn)5.0
xAxis.yOffset = 5.0
//繪制x軸的標(biāo)簽。默認(rèn)true
xAxis.drawLabelsEnabled = true
//標(biāo)簽文字大小。默認(rèn)10
xAxis.labelFont = .systemFont(ofSize: 10)
//標(biāo)簽文字顏色。默認(rèn)black
xAxis.labelTextColor = .black
//將軸標(biāo)簽居中,而不是將它們畫在原來的位置。默認(rèn)false
xAxis.centerAxisLabelsEnabled = false
//顯示x軸的軸線。默認(rèn)true
xAxis.drawAxisLineEnabled = true
//軸線的顏色。默認(rèn)gray
xAxis.axisLineColor = .red
//軸線的寬度。默認(rèn)0.5
xAxis.axisLineWidth = 2
//默認(rèn)0
xAxis.axisLineDashPhase = 0
//軸線的虛線效果
xAxis.axisLineDashLengths = [5]
//顯示網(wǎng)格線。默認(rèn)true
xAxis.drawGridLinesEnabled = true
//網(wǎng)格線的顏色
xAxis.gridColor = .red
//網(wǎng)格線的寬度。默認(rèn)0.5
xAxis.gridLineWidth = 2
xAxis.gridLineDashPhase = 0
//網(wǎng)格線的虛線效果,間距值
xAxis.gridLineDashLengths = [5]
//粒度。為false時(shí),如果兩個(gè)相鄰的軸值四舍五入到相同的值,則軸值可能重復(fù)。默認(rèn)false
xAxis.granularityEnabled = true
//granularityEnabled = true時(shí),設(shè)置x軸標(biāo)簽顯示,例如:設(shè)置3則每隔兩個(gè)柱子顯示一個(gè)標(biāo)簽。默認(rèn)1
xAxis.granularity = 3
//x軸顯示數(shù)量,默認(rèn)6,全部顯示柱子,不可滑動(dòng)。
//搭配設(shè)置setVisibleXRangeMaximum則可滑動(dòng)。需要在設(shè)置完 barChartView.data 后設(shè)置 setVisibleXRangeMaximum
xAxis.labelCount = 6
......省略代碼
barChartView.data = data
barChartView.setVisibleXRangeMaximum(6)
//標(biāo)簽格式化,設(shè)置后則titles顯示換成0開始的序列號(hào)
let formatter = NumberFormatter();
formatter.positivePrefix = "第";
formatter.positiveSuffix = "個(gè)";
xAxis.valueFormatter = DefaultAxisValueFormatter(formatter: formatter)
let values = ["1#", "2#", "3#", "4#", "5#", "6#", "7#", "8#", "9#", "10#", "11#"]
xAxis.valueFormatter = IndexAxisValueFormatter(values: values)
xAxis.labelCount = values.count
//不強(qiáng)制繪制指定數(shù)量的label
xAxis.forceLabelsEnabled = false
//設(shè)置最小值
xAxis.axisMinimum = 2
//設(shè)置最大值
xAxis.axisMaximum = 6
//撤銷axisMinimum設(shè)置的最小值
//xAxis.resetCustomAxisMax()
//撤銷axisMaximum設(shè)置的最大值
//xAxis.resetCustomAxisMin()
//第一條數(shù)據(jù)距最左端距離,相當(dāng)于偏移幾個(gè)單位量。默認(rèn)0.5
xAxis.spaceMin = 2
//最后一條數(shù)據(jù)距最左端距離,相當(dāng)于偏移幾個(gè)單位量。默認(rèn)0.5
xAxis.spaceMax = 2
//x軸標(biāo)簽文字傾斜度(圖表會(huì)上移)。默認(rèn)0.0
xAxis.labelRotationAngle = .pi * 8
//x軸第一個(gè)和最后一個(gè)標(biāo)簽條目超過圖表邊緣時(shí)剪切。默認(rèn)false
xAxis.avoidFirstLastClippingEnabled = false
//x軸文字位置。默認(rèn)top
xAxis.labelPosition = .bottom
//x軸標(biāo)簽文字換行。默認(rèn)false
xAxis.wordWrapEnabled = true
//wordWrapEnabled == true時(shí),x軸標(biāo)簽顯示寬度的百分比。默認(rèn)1.0
xAxis.wordWrapWidthPercent = 1.0
//限制線位置。true時(shí),線在圓柱后面。false時(shí),線在圓柱前面。默認(rèn)false
xAxis.drawLimitLinesBehindDataEnabled = false
//添加限制線
let limit7 = ChartLimitLine(limit: 7, label: "7");
//添加到Y(jié)軸上
xAxis.addLimitLine(limit7)
//
////添加限制線
let limit3 = ChartLimitLine(limit: 3, label: "3");
limit3.lineDashLengths = [6]
limit3.lineColor = .orange
limit3.valueTextColor = .red
limit3.lineWidth = 5
limit3.labelPosition = .bottomLeft
limit3.valueFont = .systemFont(ofSize: 20)
//添加到Y(jié)軸上
xAxis.addLimitLine(limit3)
leftAxis
y軸
屬性參考
xAxis
//偏移量。改變值時(shí)圖表位置不變,y軸標(biāo)簽文字右移距離的大小。默認(rèn)5.0
leftAxis.xOffset = 5.0
//y軸最大值
leftAxis.axisMaximum = 100
//y值最小值,不設(shè)置此值在stacked時(shí),圓柱懸空(不從x軸線開始)
leftAxis.axisMinimum = 0
//顯示y軸底部標(biāo)簽項(xiàng),默認(rèn)true
leftAxis.drawBottomYLabelEntryEnabled = true
//顯示y軸頂部標(biāo)簽項(xiàng),默認(rèn)true
leftAxis.drawTopYLabelEntryEnabled = true
//柱狀圖是否倒置,默認(rèn)false
leftAxis.inverted = true
//是否顯示y軸零線。默認(rèn)false
leftAxis.drawZeroLineEnabled = true
//y軸零線顏色。默認(rèn)gray
leftAxis.zeroLineColor = .red
//y軸零線寬度。默認(rèn)1.0
leftAxis.zeroLineWidth = 5
//默認(rèn)0.0
leftAxis.zeroLineDashPhase = 0
//y軸零線虛線效果
leftAxis.zeroLineDashLengths = [5, 8]
barChartView.backgroundColor = .lightGray
//最大值到頂部所占整個(gè)軸的百分比,默認(rèn)0.1
leftAxis.spaceTop = 0.5
//最小值到底部所占整個(gè)軸的百分比,默認(rèn)0.1
leftAxis.spaceBottom = 0.3
//y軸標(biāo)簽的顯示位置
leftAxis.labelPosition = .outsideChart
//y軸文字的對(duì)齊方式
leftAxis.labelAlignment = .left
//y軸標(biāo)簽的水平偏移量。大于0則y軸標(biāo)簽文字往右移動(dòng),小于0往左
leftAxis.labelXOffset = 10
//y軸最小寬度
leftAxis.minWidth = 20
//y軸最大寬度
leftAxis.maxWidth = 50
rightAxis
let rightAxis = barChartView.rightAxis
屬性參考
leftAxis
data
BarChartDataSet
let set = BarChartDataSet(entries: entries, label: "圖例")
//圓柱顏色
set.setColor(.red)
let formatter = NumberFormatter()
formatter.positiveSuffix = "%"
formatter.positivePrefix = "+"
set.valueFormatter = DefaultValueFormatter(formatter: formatter)
//高亮顯示
set.highlightEnabled = true
//高亮顯示顏色
set.highlightColor = .purple
//高亮顏色透明度
set.highlightAlpha = 0.6
//圓柱邊寬。默認(rèn)0.0
set.barBorderWidth = 3
//圓柱邊色。默認(rèn)black
set.barBorderColor = .red
//圓柱陰影色。(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
set.barShadowColor = .orange
//圓柱上是否顯示文字
set.drawValuesEnabled = false
BarChartData
//顯示柱狀圖頂部文字。默認(rèn)true
data.setDrawValues(true)
data.setValueFont(.systemFont(ofSize: 20))
data.setValueTextColor(.red)
//圓柱和間距的比例,默認(rèn)0.85
data.barWidth = 0.3
單柱
var entries = [BarChartDataEntry]()
for i in 0...10 {
let entry = BarChartDataEntry(x: Double(i), y: Double(arc4random_uniform(50)))
entries.append(entry)
}
let set = BarChartDataSet(entries: entries, label: "圖例")
let data = BarChartData(dataSet: set)
barChartView.data = data
GroupData
let datas: [[Double]] = [[78, 32, 23, 35, 78, 15], [12, 22, 57, 8, 56, 28], [19, 67, 35, 21, 57, 20]]
var dataSetMax: Double = 0
let groupSpace = 0.4
let barSpace = 0.03
//柱子寬度((barSpace + barWidth) * 系列數(shù) + groupSpace = 1.00 -> interval per "group")
let barWidth = 0.17
var dataSets = [BarChartDataSet]()
for i in 0..<datas.count {
var yValues = [BarChartDataEntry]()
var set = BarChartDataSet()
let data = datas[i]
for j in 0..<data.count {
let value = data[j]
dataSetMax = max(value, dataSetMax)
yValues.append(BarChartDataEntry(x: Double(j), y: value))
set = BarChartDataSet(entries: yValues, label: "第\(i)個(gè)圖例")
set.setColor(UIColor(red: CGFloat(arc4random() % 256) / 255.0, green: CGFloat(arc4random() % 256) / 255.0, blue: CGFloat(arc4random() % 256) / 255.0, alpha: 1.0))
set.valueColors = [.red]
}
dataSets.append(set)
}
dataSetMax = (dataSetMax + dataSetMax * 0.1)
barChartView.leftAxis.axisMaximum = dataSetMax
barChartView.leftAxis.axisMinimum = 0
let data = BarChartData(dataSets: dataSets)
data.barWidth = barWidth
data.groupBars(fromX: -0.5, groupSpace: groupSpace, barSpace: barSpace)
barChartView.data = data
StackedData
let datas: [[Double]] = [[30, 30, 30], [35, 78, 15], [12, 22, 57], [8, 56, 28], [19, 67, 35]]
let stackLabels = ["Label1", "Label2", "Label3"]
var entries = [BarChartDataEntry]()
for i in 0..<datas.count {
var total: Double = 0
let data = datas[i]
for j in 0..<data.count {
total += data[j]
}
var num: Double = 0
var yValues = [Double]()
for i in 0..<data.count {
num = data[i] * 100.0 / total
yValues.append(num)
}
let entry = BarChartDataEntry(x: Double(i), yValues: yValues)
entries.append(entry)
}
let set = BarChartDataSet(entries: entries, label: "圖例")
set.stackLabels = stackLabels
set.colors = ChartColorTemplates.vordiplom()
let data = BarChartData(dataSet: set)
barChartView.data = data
IChartAxisValueFormatter
barChartView.xAxis.valueFormatter = self
自定義 x軸 文字
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return "#\(value)"
}
ChartViewDelegate
barChartView.delegate = self
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
// 點(diǎn)擊
}
func chartValueNothingSelected(_ chartView: ChartViewBase) {
// 沒有選擇任何內(nèi)容或取消選擇
}
func chartViewDidEndPanning(_ chartView: ChartViewBase) {
// 停止在圖表上的值之間移動(dòng)
}
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
// 縮放圖表
}
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
// 拖動(dòng)手勢(shì)移動(dòng)/轉(zhuǎn)換圖表
}
func chartView(_ chartView: ChartViewBase, animatorDidStop animator: Animator) {
// 停止動(dòng)畫
}
TIPS
如果圖表數(shù)據(jù)為空仍想展示圖表,暫時(shí)沒找到其它方法,下面也算是曲線救國吧。如果您有好的辦法希望可以私信告訴我,謝謝。
判斷 entries
為空時(shí),添加一條數(shù)據(jù) BarChartDataEntry(x: -10000, y: -10000)
,記得設(shè)置 axisMinimum
和 axisMaximum
barChartView.xAxis.axisMinimum = 0
barChartView.xAxis.axisMaximum = 100
barChartView.leftAxis.axisMinimum = 0
barChartView.leftAxis.axisMaximum = 200
barChartView.rightAxis.enabled = false
var entries = [BarChartDataEntry]()
for i in 0...10 {
let entry = BarChartDataEntry(x: Double(i), y: Double(arc4random_uniform(50)))
// entries.append(entry)
}
if entries.isEmpty {
entries.append(BarChartDataEntry(x: -10000, y: -10000))
}
let set = BarChartDataSet(entries: entries, label: "圖例")
let data = BarChartData(dataSet: set)
barChartView.data = data
2022.07.28 更新
在此感謝大佬 lchenwanli 對(duì)于我和 那些傲慢的404 問題的回復(fù),
設(shè)置柱體成圓角
BarChartRenderer
類中方法 @objc open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int) { }
中 context.fill(barRect)
代碼注釋掉,換成如下代碼:
context.beginPath()
context.move(to: CGPoint(
x: barRect.origin.x,
y: barRect.origin.y))
// 右上
context.addArc(tangent1End: CGPoint(x: barRect.origin.x + barRect.width, y: barRect.origin.y),
tangent2End: CGPoint(x: barRect.origin.x + barRect.width, y: barRect.origin.y + barRect.height), radius: 12);
// 右下
context.addArc(tangent1End: CGPoint(x: barRect.origin.x + barRect.width, y: barRect.origin.y + barRect.height),
tangent2End: CGPoint(x: barRect.origin.x, y: barRect.origin.y + barRect.height), radius: 12);
// 左下
context.addArc(tangent1End: CGPoint(x: barRect.origin.x, y: barRect.origin.y + barRect.height),
tangent2End: CGPoint(x: barRect.origin.x, y: barRect.origin.y), radius: 12);
// 左上
context.addArc(tangent1End: CGPoint(x: barRect.origin.x, y: barRect.origin.y),
tangent2End: CGPoint(x: barRect.origin.x + barRect.width, y: barRect.origin.y), radius: 3);
context.fillPath()