How to add shortcuts to XAxis for BarChartView in ios-chart

I added a chart to the storyboard, but I can’t correctly set labels for my data records.

here is my code:

var names = ["aaa", "bbb", "ccc", "ddd"] var values = [230.0, 280.0, 450.0, 340.0] setChart(dataPoints: names, values: values) 

setChart:

 func setChart(dataPoints: [String], values: [Double]) { let formatter = BarChartFormatter() formatter.setValues(values: dataPoints) let xaxis:XAxis = XAxis() barChartView.noDataText = "You need to provide data for the chart." var dataEntries: [BarChartDataEntry] = [] for i in 0..<dataPoints.count { let dataEntry = BarChartDataEntry(x: Double(i), y: values[i]) dataEntries.append(dataEntry) } let chartDataSet = BarChartDataSet(values: dataEntries, label: "Ω…ΩˆΨ¬ΩˆΨ―ΫŒ") let chartData = BarChartData(dataSet: chartDataSet) xaxis.valueFormatter = formatter barChartView.xAxis.labelPosition = .bottom barChartView.xAxis.drawGridLinesEnabled = false barChartView.xAxis.valueFormatter = xaxis.valueFormatter barChartView.chartDescription?.enabled = false barChartView.legend.enabled = true barChartView.rightAxis.enabled = false barChartView.data = chartData } 

and finally formatting:

 @objc(BarChartFormatter) public class BarChartFormatter: NSObject, IAxisValueFormatter { var names = [String]() public func stringForValue(_ value: Double, axis: AxisBase?) -> String { return names[Int(value)] } public func setValues(values: [String]) { self.names = values } } 

but this did not work as shown below:

enter image description here

as shown here, it adds 6 tags instead of 4 tags, and also has duplicates.

I already read this solution , however, as you can see, it has some problems.

How can I solve this problem?

+5
source share
1 answer

I think you can try setting the following properties:

 barChartView.xAxis.granularityEnabled = true barChartView.xAxis.granularity = 1.0 //default granularity is 1.0, but it is better to be explicit barChartView.xAxis.decimals = 0 

The source code says a lot about the properties above. https://github.com/danielgindi/Charts/blob/master/Source/Charts/Components/AxisBase.swift

+9
source

Source: https://habr.com/ru/post/1257967/


All Articles