[英]Swift: Bar chart content not centerd horizontally
我使用Daniel Gindi的庫char https://github.com/danielgindi/Charts
我有一個問題,我無法將內容圖表水平居中
我的代碼:
private func setup(xValue: [String]) {
noDataText = "No data"
xAxis.drawGridLinesEnabled = false
xAxis.labelPosition = .bottom
xAxis.valueFormatter = IndexAxisValueFormatter(values: xValue)
xAxis.granularity = 1
xAxis.granularityEnabled = true
xAxis.labelCount = xValue.count
xAxis.axisMinimum = 0.0
xAxis.axisMaximum = Double(xValue.count)
leftAxis.spaceTop = 0.35
leftAxis.axisMinimum = 0
leftAxis.drawGridLinesEnabled = false
rightAxis.enabled = false
}
並創建圖表:
private func setChart(xValue: xAxisValue, values: [SBChartEntry]) {
let dataSets: [BarChartDataSet] = values.map {
let set = BarChartDataSet(entries: $0.value.enumerated().map { index, element in
BarChartDataEntry(x: Double(index), y: element)
}, label: $0.name)
set.colors = [$0.color]
return set
}
let chartData = BarChartData(dataSets: dataSets)
let groupSpace: Double = (values.count > 1) ? 0.7 / (Double(values.count) * 2.2) : 0.6
let barSpace = (values.count > 1) ? 0.05 : 0
let barWidth: Double = (values.count > 1) ? 0.75 / Double(values.count) : 0.4
chartData.barWidth = barWidth
if values.count > 1 {
xAxis.centerAxisLabelsEnabled = true
chartData.groupBars(fromX: Double(0), groupSpace: groupSpace, barSpace: barSpace)
} else {
// For one bar
}
notifyDataSetChanged()
data = chartData
//chart animation
animate(xAxisDuration: 1, yAxisDuration: 1, easingOption: .linear)
}
我無法配置圖表僅包含一個數組(因此只有一個條形)的時間
謝謝
解:
private func setChart(xValue: xAxisValue, values: [SBChartEntry]) {
let dataSets: [BarChartDataSet] = values.map {
let set = BarChartDataSet(entries: $0.value.enumerated().map { index, element in
BarChartDataEntry(x: Double(index), y: element)
}, label: $0.name)
set.colors = [$0.color]
return set
}
let chartData = BarChartData(dataSets: dataSets)
let groupSpace: Double = (values.count > 1) ? 0.7 / (Double(values.count) * 2.2) : 0.9
let barSpace = (values.count > 1) ? 0.05 : 0.9
let barWidth: Double = (values.count > 1) ? 0.75 / Double(values.count) : 0.5
chartData.barWidth = barWidth
if values.count > 1 {
xAxis.axisMinimum = 0.0
xAxis.centerAxisLabelsEnabled = true
} else {
xAxis.axisMinimum = -1 // I Added this
}
chartData.groupBars(fromX: Double(0), groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
data = chartData
//chart animation
animate(xAxisDuration: 1, yAxisDuration: 1, easingOption: .linear)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.