I use Daniel Gindi's library char https://github.com/danielgindi/Charts
I have a problem I can not center the content chart horizontally
My code:
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
}
And to create the chart:
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)
}
I can not configure when the chart contains only one array (so only one bar)
Thanks
Solution:
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.