我在使用 iOS 图表库为 xAxis 创建字符串值时遇到问题
x值总是有重复值,看下图,你可以看到值总是JAN JAN JAN JAN FEB FEB FEB
我如何设置图表的 x 值,因为它将显示 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 formatoineChartFormatter = 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
}
}
Best Answer-推荐答案 strong>
首先,使用粒度 来避免重复值。
其次,如果您发现它们的值非常不同,请检查您的 valueFormatter 不要返回相同的字符串。例如int(1.5) 和 int(1.9) 会给你相同的 Jan 但你可能想让 1.9 返回二月
同样,如果要处理小数,则必须仔细实现自己的 valueFormatter
关于iOS swift3 Chart xaxis重复值问题,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/45665965/
|