Reputation: 3104
I have this simple implementation of charts for iOS. And I'm looking for a way to align the labels at the center of each bar.
What I've accomplished so far was to position the labels inside each bar. I'm stuck at this point, as I don't see any way to achieve centering the label.
Here is a screenshot of what I've accomplished.
A snippet of the code used to setup this view.
func prepareHorizontalBarChart() {
var entries1 = [BarChartDataEntry]()
var entries2 = [BarChartDataEntry]()
var entries3 = [BarChartDataEntry]()
let values:[String] = ["1/22", "1/25", "1/30"]
let bar1 = BarChartDataEntry(x: Double(0), y: Double(4), icon: nil, data: "1/22" as AnyObject)
entries1.append(bar1)
let bar2 = BarChartDataEntry(x: Double(1), y: Double(6))
entries2.append(bar2)
let bar3 = BarChartDataEntry(x: Double(2), y: Double(2))
entries3.append(bar3)
let set1 = BarChartDataSet(values: entries1, label: "test")
set1.drawIconsEnabled = false
let set2 = BarChartDataSet(values: entries2, label: "test")
set1.drawIconsEnabled = false
let set3 = BarChartDataSet(values: entries3, label: "test")
set1.drawIconsEnabled = false
set1.colors = [UIColor.purple]
set2.colors = [UIColor.magenta]
set3.colors = [UIColor.red]
let data = BarChartData(dataSets: [set1, set2, set3])
data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 10))
data.barWidth = 0.2
let formatter = NumberFormatter()
formatter.numberStyle = .none
formatter.maximumFractionDigits = 0
formatter.multiplier = 1.0
let defaultValueFormatter = DefaultValueFormatter(formatter: formatter)
data.setValueFormatter(defaultValueFormatter)
horizontalBarChart.zoomOut()
horizontalBarChart.fitBars = true
horizontalBarChart.data = data
horizontalBarChart.xAxis.drawGridLinesEnabled = false // disable horizontal grid lines
// horizontalBarChart.xAxis.enabled = false
horizontalBarChart.chartDescription?.enabled = false
horizontalBarChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: values)
horizontalBarChart.xAxis.labelPosition = .bottom
horizontalBarChart.rightAxis.enabled = false
horizontalBarChart.leftAxis.axisMinimum = 0
horizontalBarChart.legend.verticalAlignment = .top
horizontalBarChart.legend.horizontalAlignment = .center
horizontalBarChart.legend.orientation = .vertical
horizontalBarChart.drawValueAboveBarEnabled = false
horizontalBarChart.legend.enabled = false
horizontalBarChart.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
}
Upvotes: 1
Views: 1641
Reputation: 264
Goto Charts and look for HorizontalBarChartRender
class, find a method called draw values and changed value for text alignment to center.
or: Search for these two lines
let x = transformed[k].x + (drawBelow ? negOffset : posOffset)
replace it with
let x = buffer.rects[k].origin.x + buffer.rects[k].size.width / 2.2
if !viewPortHandler.isInBoundsTop(rect.origin.y) { break }
comment out this line
Upvotes: 1