You need to use an array of ChartDataEntry
to represent your data. ChartDataEntry
takes a x
and y
, each being a Double
.
Option 1 - Time-based x-axis
If you would like to represent data points that are horizontally spaced according to dates, you'll need to Convert your dates to TimeInterval, e.g. using Date.timeIntervalSince1970
. The timeInterval from this conversion will become the x value of the data point.
There's actually an example of this in the demo project of the Charts library - LineChartTimeViewController.swift
:
let now = Date().timeIntervalSince1970 // Here's the date to interval conversion
let hourSeconds: TimeInterval = 3600
let from = now - (Double(count) / 2) * hourSeconds
let to = now + (Double(count) / 2) * hourSeconds
let values = stride(from: from, to: to, by: hourSeconds).map { (x) -> ChartDataEntry in
let y = arc4random_uniform(range) + 50
return ChartDataEntry(x: x, y: Double(y))
}
Option 2 - Index-based x-axis
If you're fine with the data points being equally spaced, then just create the ChartDataEntry
array using the indices of your original array for the x values. For example:
for (index, point) in Swim.enumerated() {
let entry = ChartDataEntry(x: index, y: point[1])
data.append(entry)
}
Formatting the x-axis
For either option, you'll need to implement the IAxisValueFormatter
protocol in order to format the x axis labels
For option 1, you can use the value
directly, converting it back to a date, then formatting it to your desired string
For option 2, the value
will represent the index of the datapoint in the original array, you access it via something like:
let date = Swim[value][0]