Reputation: 389
I am trying to put labels in barchart using ios-chart 3.0 with no success. My labels are dinamically showed, are no fixed as months.
let chartDataSet = BarChartDataSet(values: dataEntries, label: "animals")
let chartData = BarChartData(xVals: animalsArray, dataSet: chartDataSet)
The last line shows "Cannot invoke initializer for type 'BarChartData' with an argument list of type '(xVals: [String], dataSet: BarChartDataSet)'"
Upvotes: 1
Views: 629
Reputation: 813
I struggled a bit with this problem too. If I understand it correctly, starting with iOS-Charts 3.0, you can't pass x and y values at the same time, so most tutorials you find online, written for version 2.x, point you in the wrong direction (you can't use BarChartData(xVals: dataSet:)
anymore).
On top of that, the fact that the documentation is Android-only, and that the sample code uses cryptic variable names, doesn't help a beginner like me figure this out from the sample project, but I guess I did, since now I'm able to have custom Strings as labels. Here's how:
Conform your class to the IAxisValueFormatter
protocol:
class ChartsViewController : UIViewController, IAxisValueFormatter {//...}
Add a property to your class for the string labels, and initialize it (either hard-coding its values as in the following example, or by setting them in your viewDidLoad:
):
var labelStrings : Array<String> = ["these", "will", "be", "your", "labels"]
Implement the required stringForValue:
method of IAxisValueFormatter
:
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return labelStrings[Int(value) % labelStrings.count]}
In your custom "configure chart" method create an XAxis object, set its valueFormatter to self (so the stringForValue:
above is called) and set the chartView.valueFormatter equal as the Axis.valueFormatter:
let xAxis = XAxis()
xAxis.valueFormatter = self
barChartView.xAxis.valueFormatter = xAxis.valueFormatter
With the points above, you got the custom labels on the X axis, but of course you still have to set the values for Y; just in case someone else comes here for an answer in the future, here's the code to set those values too:
let yValues = myArrayOfCustomValues.enumerated().map { index, element -> BarChartDataEntry in
return BarChartDataEntry(x: Double(index), y: element)
}
let chartDataSet = BarChartDataSet(values: yValues, label: "If you want a label; you can also pass nil")
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData
Upvotes: 2