I am pretty new to SwiftUII and having trouble understanding how the Plottable value works in SwiftUIChart?
I have a simple line chart to show step count.
If I define LineMark's x
value without unit i.e. value("Week Day", $0.weekday)
then plotted data is aligned with x-axis.
But,
if I define LineMark's x
value with unit i.e value("Week Day", $0.weekday, unit: .day)
the x-axis does not align with the plotted value’s "date". Meaning that the line get plotted from between the first and second x-axis value.Since the first data from the chart's data array has the date as Jul 17, I was under impression that the line should start from x-axis having value Jul 17, instead is doesn't. If I remove unit then, the line start from Jul 17.
struct StepCount: Identifiable {
let id = UUID()
let weekday: Date
let steps: Int
init(day: String, steps: Int) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
self.weekday = formatter.date(from: day) ?? Date.distantPast
self.steps = steps
}
}
let currentWeek: [StepCount] = [
StepCount(day: "20220717", steps: 5000),
StepCount(day: "20220718", steps: 15000),
StepCount(day: "20220719", steps: 5000),
StepCount(day: "20220720", steps: 10800),
StepCount(day: "20220721", steps: 5300),
StepCount(day: "20220722", steps: 10400),
StepCount(day: "20220723", steps: 4000)
]
struct LineChart: View {
var body: some View {
VStack {
GroupBox ( "Line Chart - Step Count") {
Chart {
ForEach(currentWeek) {
LineMark(
x: .value("Week Day", $0.weekday),
y: .value("Step Count", $0.steps)
)
}
}
.chartYAxis {
AxisMarks(position: .leading)
}
.chartXAxis {
AxisMarks(preset: .aligned, values: .stride(by: .day))
}
}
}
}
}