3

I have an issue creating a string value for xAxis using the iOS Charts library

x value always has duplicate value, see following picture, you can see value always be JAN JAN JAN JAN FEB FEB FEB

How I can setup chart's x value as it will show JAN FEB MAR ?

import UIKit
import Charts
class ViewController: UIViewController {
var months:[String]!
@IBOutlet var lineChartView: LineChartView!

override func viewDidLoad() {
super.viewDidLoad()


let unitsSold = [20.0, 4.0, 6.0]

var months = ["Jan", "Feb", "Mar"]

let formato:LineChartFormatter = LineChartFormatter(labels: months)
let xaxis:XAxis = XAxis()

var dataEntries: [ChartDataEntry] = []

for i in 0..<unitsSold.count {
let dataEntry = ChartDataEntry(x: Double(i), y: unitsSold[i])

print("double \(Double(i))")
dataEntries.append(dataEntry)
}

xaxis.valueFormatter = formato
let data = LineChartData()
let dataset = LineChartDataSet(values: dataEntries, label: "Hello")
dataset.colors = [NSUIColor.red]
data.addDataSet(dataset)


self.lineChartView.gridBackgroundColor = NSUIColor.white
self.lineChartView.xAxis.drawGridLinesEnabled = true;
self.lineChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
self.lineChartView.xAxis.centerAxisLabelsEnabled = true
self.lineChartView.chartDescription?.text = "LineChartView Example"
self.lineChartView.xAxis.valueFormatter = xaxis.valueFormatter
self.lineChartView.data = data
}

override open func viewWillAppear(_ animated: Bool) {
self.lineChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
}
}

@objc(LineChartFormatter)
public class LineChartFormatter: NSObject, IAxisValueFormatter{
var labels: [String] = []

public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return labels[Int(value)]
}

init(labels: [String]) {
super.init()
self.labels = labels
}
}

enter image description here

DevB2F
  • 4,674
  • 4
  • 36
  • 60
user2845478
  • 223
  • 4
  • 10

2 Answers2

2

First, use granularity to avoid duplicated values. Second, check your valueFormatter not to return same string if you found their values are very different. e.g. int(1.5) and int(1.9) will give you same Jan but you may want to let 1.9 return Feb

Again, you have to carefully implement your own valueFormatter if you are handling decimals

Wingzero
  • 9,644
  • 10
  • 39
  • 80
2

add this two lines in your code

lineChartView.xAxis.granularityEnabled = true
            lineChartView.xAxis.granularity = 1.0
Bikesh Thakur
  • 846
  • 7
  • 22