我在使用iOS Charts库
为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 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
}
}
答案 0 :(得分:1)
首先,使用granularity
来避免重复的值。
其次,如果您发现它们的值非常不同,请检查您的valueFormatter
不要返回相同的字符串。例如int(1.5)
和int(1.9)
会给您同样的Jan
,但您可能希望1.9
返回Feb
同样,如果要处理小数,则必须仔细实现自己的valueFormatter
答案 1 :(得分:1)
在代码中添加这两行
lineChartView.xAxis.granularityEnabled = true
lineChartView.xAxis.granularity = 1.0