I am trying to add a Date/String as the xAxis labels in Charts (needs to have equal space in between labels)
I am doing below but the x in the constructor only expects a double.
Any idea?
for i in 0..<self.grahEntries.count {
let x1 = self.grahEntries[i].x
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYY-MM-DD HH:mm:ss"
let date = dateFormatter.date(from: x1)
print(date)
let dataEntry = ChartDataEntry(x: date, y: self.grahEntries[i].y)//HERE IS MY PROBLEM!! xAxis is only double
dataEntries.append(dataEntry)
}
let line1 = LineChartDataSet(values: dataEntries, label: "Units Consumed")
line1.colors = [NSUIColor.blue]
line1.mode = .cubicBezier
line1.cubicIntensity = 0.2
let gradient = getGradientFilling()
line1.fill = Fill.fillWithLinearGradient(gradient, angle: 90.0)
line1.drawFilledEnabled = true
let data = LineChartData()
data.addDataSet(line1)
mChart.data = data
mChart.setScaleEnabled(false)
mChart.animate(xAxisDuration: 1.5)
mChart.xAxis.valueFormatter = DateAxisValueFormatter()
mChart.xAxis.granularity = 1.0
mChart.drawGridBackgroundEnabled = false
mChart.xAxis.drawAxisLineEnabled = false
mChart.xAxis.drawGridLinesEnabled = false
mChart.leftAxis.drawAxisLineEnabled = true
mChart.leftAxis.drawGridLinesEnabled = true
mChart.rightAxis.drawAxisLineEnabled = false
mChart.rightAxis.drawGridLinesEnabled = false
mChart.legend.enabled = false
mChart.xAxis.enabled = true
mChart.leftAxis.enabled = true
mChart.rightAxis.enabled = false
mChart.xAxis.labelPosition = .bottom
mChart.xAxis.drawLabelsEnabled = true
mChart.xAxis.drawLimitLinesBehindDataEnabled = true
mChart.xAxis.avoidFirstLastClippingEnabled = true
UPDATE :
I did as @ces said its spreading them accurately but I still cant see labels. I updated my code above to show table
If you want the data to be spaced evenly (i.e. not representing an accurate timeline) then the answer is simpler.
Change your for
loop to
var dates: [String] = []
for i in 0..<self.grahEntries.count {
let x1 = self.grahEntries[i].x
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYY-MM-DD HH:mm:ss"
let date = dateFormatter.date(from: x1)
dates.append(date)
let dataEntry = ChartDataEntry(x: Double(i), y: self.grahEntries[i].y)
dataEntries.append(dataEntry)
}
and change
mChart.xAxis.valueFormatter = DateAxisValueFormatter(dates)
Then change DataAxisValueFormatter
to accept an array of strings in the constructor and store them. Change
func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
let i = Int(value)
return dates[i]
}