我正在使用danielgindi / Charts库,并且试图将Y值放在X轴下。
我的代码:
private func setupBarChart(){
var barChart = BarChartView(frame: frame)
barChartContainer.addSubview(barChart)
let labels = ["Ericsson", "Siemens", "Huawei", "Ericsson", "Siemens"]
barChartContainer.addConstraintsWithFormat("H:|[v0]|", views: barChart)
barChartContainer.addConstraintsWithFormat("V:|[v0]|", views: barChart)
let entry1 = BarChartDataEntry(x: 0, y: 3670)
let set1 = BarChartDataSet(values: [entry1], label: labels[0])
set1.setColor(UIColor.cnBlue)
let entry2 = BarChartDataEntry(x: 1, y: 2292)
let set2 = BarChartDataSet(values: [entry2], label: labels[1])
set2.setColor(UIColor.cnBlue)
let entry3 = BarChartDataEntry(x: 2, y: 3670)
let set3 = BarChartDataSet(values: [entry3], label: labels[2])
set3.setColor(UIColor.cnBlue)
let entry4 = BarChartDataEntry(x: 3, y: 2292)
let set4 = BarChartDataSet(values: [entry4], label: labels[3])
set4.setColor(UIColor.cnBlue)
let entry5 = BarChartDataEntry(x: 4, y: 675)
let set5 = BarChartDataSet(values: [entry5], label: labels[4])
set5.setColor(UIColor.cnBlue)
let data = BarChartData(dataSets: [set1, set2, set3, set4, set5])
barChart.data = data
barChart.drawGridBackgroundEnabled = false
barChart.drawValueAboveBarEnabled = false
barChart.drawBordersEnabled = false
barChart.legend.enabled = false
barChart.chartDescription?.text = "Sites per technology"
barChart.chartDescription?.textAlign = .center
barChart.chartDescription?.position = CGPoint(x: barChartContainer.bounds.width/2, y: 0)
barChart.xAxis.labelPosition = .bottom
barChart.xAxis.drawGridLinesEnabled = false
barChart.xAxis.wordWrapEnabled = true
barChart.xAxis.labelFont = .cnFont(ofSize: 14, weight: .semibold)
barChart.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
return labels[Int(index)]
})
barChart.leftAxis.enabled = false
barChart.rightAxis.enabled = false
barChart.drawValueAboveBarEnabled = false
barChart.doubleTapToZoomEnabled = false
barChart.pinchZoomEnabled = false
barChart.scaleXEnabled = false
barChart.scaleYEnabled = false
barChart.setExtraOffsets(left: 10, top: 10, right: 10, bottom: 10)
barChart.fitBars = true
barChart.animate(xAxisDuration: 1, yAxisDuration: 1, easingOption: .easeInOutCirc)
}
我是否必须创建一个自定义AxisRenderer,如果可以,我可以为此提供一些线索吗?我一直在寻找示例,但是我仍然无法理解如何使用渲染器获得所需的东西。
提前谢谢!
答案 0 :(得分:2)
您可以通过这种方式实现IAxisValueFormatter协议
struct Label {
var text: String
var value: Double
}
public class DayAxisValueFormatter: NSObject, IAxisValueFormatter {
var xToY = [Double: Label]()
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return "\(xToY[value]!.text ),\n\(xToY[value]!.value)"
}
}
然后将此格式化程序分配给x轴
let f = DayAxisValueFormatter(chart: chartView)
f.xToY = [
0: Label(text: "Biemens", value: 6354),
1: Label(text: "Siemens", value: 2344),
2: Label(text: "Ericsson", value: 2345),
3: Label(text: "Huawei", value: 5241),
4: Label(text: "Shmericsson", value: 3525)
]
barChart.xAxis.valueFormatter = f